开发者

What is the correct way of returning a NSArray of objects in Objective-C?

I have a method that needs开发者_如何转开发 to return an array of objects. The way it does that now is:

  1. Create a NSMutableArray*
  2. Each object, following some computation, is alloc-d and init-ed
  3. Each object, after initialization, is added to the array with addObject
  4. The array is returned

Is autoreleasing the array the right thing to do? What about the objects inside the array? When should these be released?


Yes, setting the array to autorelease before you return it is a reasonable thing to do. Also, if you are calling alloc and init on the things that you put into the array, you should call release (or autorelease) on each one after you add it to the array. Your objects will still be retained as long as they are in the array. Removing them from the array (or releasing the array) will cause them to be released.


Your method should set the array to autorelease and then the caller should retain the returned array. So the method is no longer responsible for the array, the caller is.

The objects in the array will be retained by NSMutableArray, so you should set them to autorelease so they don't leak.

- (NSMutableArray*) calleeMethod
{
    // this method is retaining the array temporarily
    // someone else is responsible for retaining it
    NSMutableArray * newArray = [[[NSMutableArray alloc] init] autorelease];

    // add some objects
    for (int i = 0; i < 10; i++)
    {
        // autorelease these objects because newArray will retain each item and 
        // is responsible for the items
        FooObject * newFooObject = [[[FooObject alloc] initWithNumber:i] autorelease];
        [newArray addObject:newFooObject];
    }

    return newArray;
}

- (void) callerMethod
{
    // retain the returned array, because we own it 
    mNewArray = [[self calleeMethod] retain];

    // do stuff 

    // make sure you explicitly release mNewArray later (probably in the dealloc)
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜