开发者

should I release NSString instance I didn't create?

开发者 https://www.devze.com 2023-02-08 03:19 出处:网络
For example, string was returned from NSDictionary, which in turn read it from file system. So, we don\'t know whether string was created through [NSString stringWith...] or [[NSString alloc] initWith

For example, string was returned from NSDictionary, which in turn read it from file system.

So, we don't know whether string was created through [NSString stringWith...] or [[NSString alloc] initWith...] or in any other way.

How do you generally know whether you 开发者_StackOverfloware responsible for releasing returned object, if API doesn't mention it?

PS I've seen similar questions here, but mostly they deal with constants @"" or explicitly created strings.


No, you should only release instances that you've alloc'd, retain'd, copy'd or new'd.


See the Cocoa Memory Management Rules. If you can only afford to read a single part of the documentation, this is the one :) And there’s also the static analyzer (Build → Build and Analyze) that’s pretty good with the memory-management rules, it should be able to catch what you miss.


The Objective-C rule of thumb: if your code performs an alloc/copy/retain to initialize an object, then you need to release it as you are the owner. If you do not perform an alloc/copy/retain to initialize an object (such as using a method to get an instance), then you are not the owner and should not release the object.

In this event, you did not create the string, so you are not responsible for releasing it. You do not need to worry how the string was initialized when it was created and added to the NSDictionary (unless you are creating and adding it to the dictionary yourself). With most collection objects, they take ownership of the objects that are added to them and so they are responsible for releasing the objects in their care.


Members of a dictionary are accessed via -objectForKey:, so you are not responsible for releasing them. The dictionary was the only object in this example that you directly created. If you did so via an alloc, copy, or new method (e.g. [[NSDictionary alloc] initWithContentsOfFile:…]) then you must release it. If it came from somewhere else including one of the [NSDictionary dictionary…] factories, you own no references to it and do not need to release it.

0

精彩评论

暂无评论...
验证码 换一张
取 消