views:

62

answers:

1

Hi all! I am worried about than am I properly adding object and releasing them.

  1. What NSMutableArray actually contain - object's copy or just a pointer to them?
  2. What is the sequence in working with NSMutableArray? (alloc, init, work, release)
  3. How to retain and release it properly?

    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
    

or I need to release all contained objects first and only than do release on NSMutableArray object?

Thanks!

+4  A: 

NSMutable array contains the reference to the object. When you add an object to NSMutableArray, it will retain the object. That is, after adding the object to the array you should release it. When you are done with that object in array, you can remove the object from the array. Upon removing, the object automatically receives a release message. So you don't need to send it another release message. And if you release the array itself, no need to send release message to all objects, as during the deallocation of NSMutableArray it will send release to all objects that it contains.

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.

Hope it helps.

taskinoor