Fred Collins
Fred Collins

Reputation: 5010

Question about autorelease object in Objective-C

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?

Upvotes: 1

Views: 445

Answers (2)

J S Rodrigues
J S Rodrigues

Reputation: 471

You have created and assigned an autoreleased object to user. By specifying autorelease you are saying that system could free it. So when it reaches the end of autorelease pool its removed from memory. That is why when you try to access it late it crashes. So if you need it to be global then you need to retain it.

Upvotes: 0

Chuck
Chuck

Reputation: 237060

Assuming that users in users = [[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 it retain to tell it you want it to stick around. And when you're finished with it, you need to send it release to 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 for users, you could do one of these:

self.users = [[MySingleton sharedClass] getUsers];
/* OR */
users = [[[MySingleton sharedClass] getUsers] retain];

The first way is usually better, but you don't want to call setters in init… or dealloc methods 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.

Upvotes: 3

Related Questions