简体   繁体   中英

Objective-c pointers and NSString

If I have this code, why doesn't the textview's text update? As far as I knew a * meant a pointer, and I haven't done a copy.

NSString *searchText = myTextView.text;

searchText = [searchText stringByReplacingOccurrencesOfString:@" " withString:@";"];

So why isn't myTextView's text changed as if I did:

myTextView.text = [searchText stringByReplacingOccurrencesOfString:@" " withString:@";"];

And how would I write the code, so that the first code example works as I intend?

The method stringByReplacing... Doesn't change the string, it returns a new string object (autoreleased, according to the naming conventions). So after the 2nd line of code, searchText points to a totally differen NSString object.

Besides, NSString objects cannot be changed, for that there's NSMutableString

If you expect to modify myTextView.text , you have to write it like your second example, and assign a new value to the property you're trying to modify. Assigning a new value to some other variable or property won't do the job - " spooky action at a distance " may work when we eventually have quantum computing, but we're not there yet. :-)

To expand a bit: Yes, searchText is a pointer. But so is myTextView.text , and when you do " searchText = myTextView.text ", you're not creating any sort of lasting relationship between the two - all you're doing is making searchText point to the same target as myTextView.text . Changing either one of them after that point will have no effect on the other. So, when you assign the result of stringByReplacing... to searchText , you're making it and only it point to a different target.

Your second example invokes the setter of the "text" property.

Your first example takes the pointer of the string, and then changes the pointer within the same scope. Hence, "text" is not changed.

BTW: Depending on how your property is defined, the setter you use will either copy, retain or assign the value you give the setter. So if you use the following:

@property(copy) NSString* text;

Then yes, the setter will copy the value you give it when you invoke:

myTextArea.text = //some string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM