NSMutableString as retain/copy

前端 未结 3 485
花落未央
花落未央 2020-11-28 02:50

I have aa number of NSMutableString\'s in my app (almost 10-11); all defined as ivar/property

@property (nonatomic, retain) NSMutableString *str1;

3条回答
  •  抹茶落季
    2020-11-28 03:32

    For mutable string copy and retain have different result. If you make a copy of str1 to str2 then any change to str1 will not reflect in str2 and any change in str2 will not reflect in str1, as they are separate object. But if str1 is retained to str2 then both are referring to same mutable string object and change via str1 will reflect in str2. But NSString is not mutable. So for simple string (that is, not mutable string) copy is just increasing the reference count, that means it is internally treated like retain (I am not 100% sure about treating copy like retain for non-mutable objects, but saw this on SO in some different question. Googling, I will edit if I can find the link.).

    And if you use copy then you still need to release that in dealloc.

    Having 10 - 11 normal sized string should have no negative effect on memory usage. A typical app may contain much more strings. By normal size I mean that you are not appending 1 million characters in a string. That will be a serious problem. The memory taken by a string will increase as the length of the string increases. Same goes for dictionary. The memory taken by the dictionary will depend on what you are storing in the dictionary. The dictionary itself don't have much overhead. You can always check the memory usages of your app by using instrument.

提交回复
热议问题