1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Copying a String (easy right?)

Discussion in 'iPhone/iPad Programming' started by XcodeNewb, Nov 17, 2009.

  1. macrumors member

    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:
    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??

  2. macrumors 603


  3. macrumors member

    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


    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.

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

    Create a property for originalText and set it to copy.

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

    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