PDA

View Full Version : Copying a String (easy right?)




XcodeNewb
Nov 17, 2009, 11:45 AM
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??


Thanks



jeremy.king
Nov 17, 2009, 12:16 PM
use initWithString: (http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/initWithString:)

XcodeNewb
Nov 17, 2009, 12:21 PM
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.

jeremy.king
Nov 17, 2009, 12:31 PM
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.

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

Luke Redpath
Nov 17, 2009, 06:31 PM
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.