Copying a String (easy right?)

Discussion in 'iOS Programming' started by XcodeNewb, Nov 17, 2009.

  1. macrumors member

    Joined:
    Feb 6, 2009
    #1
    Ok, I am running into a problem and I must be missing something simple. I am trying to 'copy' the text from a UITextView into a string to make a "backup" of the data. Then I manipulate the data in the textview and if the user doesnt like it they can revert back to the original data. The problem is that when I try and set the data of the textview back to the copy I made, the copy is now the same changed data that the textview has. How can I make a true copy of the data?

    I have tried many things, here is one example:
    Code:
    originalText = [NSString stringWithFormat:@"%@", [textView text]];
    [originalText retain];
    
    ......
    processing of the textView text
    ......
    
    ......
    User wants to revert back to original text
    ......
    
    textView.text = [NSString stringWithFormat:@"%@", originalText];
    
    The problem is that originalText has been changed and holds the manipulated data. Any ideas??


    Thanks
     
  2. macrumors 603

    jeremy.king

    Joined:
    Jul 23, 2002
    Location:
    Fuquay Varina, NC
  3. thread starter macrumors member

    Joined:
    Feb 6, 2009
    #3
    Thanks, but I have tried that as well and it performs the same way. Any time the text changes in the textview the value in the copy changes as well.
     
  4. macrumors 603

    jeremy.king

    Joined:
    Jul 23, 2002
    Location:
    Fuquay Varina, NC
    #4
    Check your code. It's not changing the value - NSString is immutable. You're changing the object reference somewhere, or have two variables pointed at the same object.

    Code:
    NSString *originalText = [[NSString alloc] initWithString: textView.text]; //copies value from view
     
    ...
     
    textView.text = [[NSString alloc] initWithString:originalText]; //copies original into view
    
     
  5. macrumors 6502a

    Joined:
    Nov 9, 2007
    #5
    Create a property for originalText and set it to copy.

    Code:
    @property (nonatomic, copy) NSString *originalText;
    
    And then:

    Code:
    self.originalText = textView.text;
    
    Manipulating textView.text will now *not* change whatever is in self.originalText as it is a completely separate mutable object.
     

Share This Page