For example, string was returned from NSDictionary
, which in turn read it from file system.
[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.
精彩评论