开发者

Deallocating NSMutableArray of custom objects

I need help with deallocation of my NSMutableArray of custom objects. I need to retain the array and so I have added a property in .h and I release it in dealloc in .m file开发者_如何学Python. When I add objects to the array, I do the following:

  myarray = [[NSMutableArray alloc] init];
  [myarray addObject:[[mycustomObject alloc]initWithObject:obj1]];
  [myarray addObject:[[mycustomObject alloc]initWithObject:obj2]];

Now, I don't know how to release mycustomobject. If I do the following:

   [myarray addObject:[[[mycustomObject alloc]initWithObject:obj1] autorelease]];

I run in to problems when I access the array later. Please advice.


I don't think you understand how memory management in Cocoa works. The array will retain the objects you add to it, and it will release them by itself when the array no longer needs them (such as when you release the array).

In other words, add the autoreleased object to the array, and don't worry about its retain count after that. If you want to remove it from the array simply remove it (using removeObjectAtIndex: or something similiar). If you think you want to release the object without removing it from the array then you are doing something wrong, since that may leave a dangling pointer in your array that will cause you to crash later.

You should really really go over the documentation again, particularly the section on Object Ownership and Disposal.


The proper way to do this is to let the array maintain ownership of the custom object:

NSMutableArray * array = [[NSMutabelArray alloc] init];

for (id obj in anArrayOfObjects) {
  mycustomObject * customObj = [[mycustomObject alloc] initWithObject:obj];
  [array addObject:customObj];
  [customObj release];
}

If you're having difficulties accessing your array later, then you're doing something wrong with the memory management of the array.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜