NSString copy not copying?

…衆ロ難τιáo~ 提交于 2019-11-28 03:25:16

问题


  NSString *myString = @"sample string";
  NSString *newString = [myString copy];

If I set a breakpoint after these two lines, the pointer for myString is the same as the pointer for newString.

WTF? Isn't NSString copy supposed to return a pointer to a new object? Or am I missing something fundamental about how copy is supposed to work?


回答1:


Since NSString is not mutable it might just internally increase ref count and be done with it.

When you release one of those NSStrings it might just decrement ref count - standard memory management.

Do you see any issues with that?




回答2:


Think about this: NSMutableString is a subclass of NSString. When your property is declared as NSString, you don't expect it to change.

Consider, if you used retain and someone gave you an NSMutableString and then later on does change it, your class will be broken.

However, you may think that always copying is slow. So NSString's copy simply calls retain. NSMutableString's copy makes an actual copy.

It is usually better to give spit out an NSString * because people won't have to copy it all the time.




回答3:


You can Allocate new variable like in sample

NSString *anotherString = [[NSString alloc] initWithString:originalString];



回答4:


It's a better practice to do copy the string value returned by a method, since the returned value maybe a mutable string object, and this value can be modified in other thread after returned by that method.



来源:https://stackoverflow.com/questions/2521468/nsstring-copy-not-copying

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