I have an instance variable called users defined as NSMutableArray.
I use that variable for fill an UITableView.
In viewDidLoad I initialize it with:
users = [[MySingleton sharedClass] getUsers];
This is the getUsers method:
- (NSMutableArray *)getUsers
{
...
NSMutableArray *listArray = [[NSMutableArray alloc] init];
for (NSDictionary *dict in jsonObject) {
...
[listArray addObject:element];
...
}
return listArray;
}
In this way all it works fine. The problem is when I set listArray as autoreleased object.
NSMutableArray *listArray = [[[NSMutableArray alloc] init] autorelease];
or
return [listArray autorelease];
Sometimes the app crash with EXC_BAD_ACCESS.
Why this? Isn’t correct set autorelease listArray?
Assuming that
usersinusers = [[MySingleton sharedClass] getUsers]is an instance variable, you’re forgetting to take ownership of the array. When you want to claim ownership of an object (such as this array), you need to send itretainto tell it you want it to stick around. And when you’re finished with it, you need to send itreleaseto tell it so. Setters handle this for you, so it’s generally a good idea to use setters outside of init and dealloc methods. So assuming you have a setter forusers, you could do one of these:The first way is usually better, but you don’t want to call setters in
init…ordeallocmethods because they might have side effects that are undesirable there. Since you’re not in one of those methods here, you can just use the first.