我担心的是我正确添加对象并释放它们。
如何正确保留和释放?
NSMutableArray *listData = [[NSMutableArray alloc] init];
int i = 0;
for (i = 0; i < 3; i++)
{
MyData *obj = [[MyData alloc] init];
NSString *name = nil;
switch (i)
{
case 0:
name = @"Semen";
break;
case 1:
name = @"Ivan";
break;
case 2:
name = @"Stepan";
break;
default:
break;
}
obj.name = name;
[listData addObject: obj];
[obj release];
}
[listData release] //in dealloc method
或者我需要首先释放所有包含的对象,而不是在NSMutableArray对象上释放?
谢谢!
答案 0 :(得分:18)
NSMutable数组包含对象的引用。将对象添加到NSMutableArray时,它将保留该对象。也就是说,在将对象添加到数组后,您应该释放它。在数组中完成该对象后,可以从数组中删除该对象。删除后,对象会自动收到释放消息。所以你不需要发送另一个发布消息。如果您释放数组本身,则无需向所有对象发送释放消息,因为在NSMutableArray的解除分配期间,它将向其包含的所有对象发送释放。
1. alloc NSMutableArray. 2. alloc object1. 3. add object1 to array. 4. release object1. 5. alloc object2. 6. add object2 to array. 7. release object2. 8. add as many objects as needed in this manner. 8. work with object1. 9. remove object1 from array. it will receive a release automatically. 10. release the array. object2 and others will receive a release.
希望它有所帮助。