Cocoa String Question

家住魔仙堡 提交于 2019-12-11 08:48:27

问题


I have a NSString and I want to write its value to a NSMutableString. Is this valid:

NSString *temp = [NSString stringWithString:@"test"];
NSMutableString *mutable = temp;

I ask because although this seems doable, I would think that this would assign both temp and mutable to the same address space. I have this question a lot when passing values into a method or returning values from a method. Sometimes I see other people do this or create the mutable string with stringWithString or initWithString. Thanks


回答1:


You can use the mutableCopy method, which creates a mutable copy of the receiver and applies to any class which adopts the NSMutableCopying protocol (of which NSString is one of them):

NSString *temp = [NSString stringWithString:@"test"];
NSMutableString *mutable = [temp mutableCopy];

This will create a mutable copy of the string, as a new string instance. In this case it doesn't apply, as temp is an autoreleased string, but you would otherwise need to release the old string that you have made a copy of, if you no longer need it.

Since mutableCopy contains "copy", then you need to memory-manage the new string (you take ownership of it according to the Apple Object Ownership Policy).

The method that you have used simply assigns mutable as a pointer to the previously instantiated NSString.




回答2:


One thing that seems to confuse a lot of people with Cocoa is the difference between variables and objects.

You have to keep in mind that when you declare a variable like NSMutableString *mutable, you are not creating a string. This is just a pointer variable of type NSMutableString*. Structurally, it's the same as any other pointer — and, as the term "pointer" implies, it just points to something that actually lives elsewhere. Because of this, you technically can assign it to point to any object. But you're not turning that object into a mutable string — you're just lying about what kind of object the variable points to. Once you try to send the object a message that only NSMutableString can respond to, the jig is up!

As Perspx said, if you have a string that you want to mutate, you can use the mutableCopy method to get — you guessed it — a mutable copy. There are also a lot of NSString methods that don't mutate the string, but let you get a new string with certain changes made (for example, stringByAppendingString:). You can go a pretty long way with those.



来源:https://stackoverflow.com/questions/1313836/cocoa-string-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!