开发者

if a method accepts objects and adds to an array, should it detect & release the object if necessary?

If I have a helper 开发者_StackOverflow社区method thats adds object to an array (NSMutableArray) in my custom class, would it make sense to do either:

  1. somehow auto-detect whether the incoming object has been already autoreleased? then if not release it after adding it to the array?
  2. in dealloc iterate through all objects in the array and somehow check they don't need to be released, and then after this release the array itself?

the concern I have is when I have to dealloc my custom class, including the array, how do I know the status of the objects within the array?


It should be the responsibility of code calling your helper method to release the objects (through autorelease or normal release) after passing them to your function. The objects being passed to you will be retained for your use by putting them in your array. When you release your array in your dealloc, all the objects in that array will be released. Make sense?

I.e. you don't need to do anything special--just add the objects to your array.


The simplest rule -- and this has been mentioned from time to time -- is that you should only release objects that you've explicitly allocated (alloc), copied (copy), newed up (new), or retained (retain). In the scenario you've described, you're not responsible for anything. If your method isn't doing any of the four aforementioned things, there's nothing to worry about.


You don't do anything in a method (other than accessor methods) to handle other objects memory. This is the whole idea of object ownership; since your method doesn't own the object you pass in, it shouldn't deal with that object's memory. NSMutableArray will deal with the objects it contains when it is dealloced, you don't have to do any of the work other than release the array when you're done with it.


somehow auto-detect whether the incoming object has been already autoreleased? then if not release it after adding it to the array?

no - collections retain the objects they add, then release them when they are removed

in dealloc iterate through all objects in the array and somehow check they don't need to be released, and then after this release the array itself?

no - collections retain the objects they add, then release them when they are removed

the concern I have is when I have to dealloc my custom class, including the array, how do I know the status of the objects within the array?

the collection will take care of it, and hold a reference to the object while it is in the collection. you are (of course) responsible for calling release on the array itself when the object that holds it removes or replaces it (e.g. in dealloc).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜