views:

199

answers:

2

Hi i'm a objC noob. I have a problem filling an NSMutableArray with objects.

for(id p in tmpArray){
    Person *person = [[Person alloc] init];
    person.usrName = p;
    [persons addObject:person]; // after this line the persons
                                // array is still empty
    [person release];
}

Persons is a property NSMutableArray and the problem is that it's empty. Is it the release of the person object too early or have I instanciated it wrong?

+2  A: 

Make sure you've alloced and initialised the array before you try to add things to it

James Raybould
+1  A: 

You need to initialize your array in the -init method, like this:

NSMutableArray *array = [[NSMutableArray alloc] init];
self.persons = array; // will be automatically retained 
                      // because you're using the property
[array release]; // we alloced - we release it

Don't forget to release it:

-(void)dealloc {
     self.persons = nil; // previous value of property 'persons' will be released
     [super dealloc];
}
Adam Woś
Please add that there are some people who use `persons = [[NSMutableArray alloc] init]` and `[persons release]`. That's because accessors could have side-effects and should therefore not be used in constructing and deconstructing. See Mike Ash's blog for a discussion: http://www.mikeash.com/?page=pyblog/friday-qa-2009-11-27-using-accessors-in-init-and-dealloc.html That `dealloc` method isn't necessary if your app is garbage-collected. (Still nice to have in case the code gets used in a non gc environment.)
Georg
Thanks, @gs. I changed the code to something I also wrote previously - somehow I prefer the explicit alloc/init/release instead of autoreleased objects.
Adam Woś
Adam Woś: That doesn't solve the problem that you're still using property accesses in `init` and `dealloc`. See my comment on the question for more detail on why this is a bug waiting to happen.
Peter Hosey
@Peter: That's been true for a long time, but more and more this is changing. Using accessors in *init* and *dealloc* can be quite convenient. See that blog post I linked to earlier: http://www.mikeash.com/?page=pyblog/friday-qa-2009-11-27-using-accessors-in-init-and-dealloc.html
Georg
Georg: Yes, it's convenient, but it's still risky, especially when you add subclasses, since they may override previously-safe accessors and make them derived properties. And I don't see what's changing; accessors are no more guaranteed-safe now than they ever have been. *Synthesized* accessors should be safe, but, again, subclasses may override those.
Peter Hosey