NSString @property, using copy instead of retain

前端 未结 3 1326
梦谈多话
梦谈多话 2020-12-05 03:09

I\'m looking over Apple\'s sample application EditableDetailView, and noticed that in one of their controllers, they\'re setting an instance of NSString property with (nonat

3条回答
  •  难免孤独
    2020-12-05 03:55

    Remember that there is an NSMutableString. It would be really bad to be able to mutate the contents of a string that some other object owns (say, by deleting half its characters), especially if you don't realize you're affecting another object. Therefore, it's nice for the other object to make its own copy.

    You may say “well, why don't I just copy the string before assigning it there?”. Maybe the object wants a mutable string and yours is immutable. If you have to copy the string first, then you have to look up which kind of string it wants in its documentation or header, then make the right kind of copy (every time). This way, you just say other.string = myString and it makes whatever kind of copy it wants—you don't have to worry about it.

提交回复
热议问题