简体   繁体   中英

Objective-C Memory Management Question, NSMutableArray

I have a UIViewController. At the top of the UIViewController, I have declared

NSMutableArray *contacts;

In my viewDidLoad method, I call [self getContacts] which basically initializes my contacts array. It begins by initializing the array, and then it adds some objects:

if(contacts == nil)
   contacts = [[NSMutableArray alloc] init];

[contacts removeAllObjects];
[contacts addObjectsFromArray:[some objects]];

So, now my contacts is initialized. In my viewDidLoad method, I even use contacts , and it works great. Later on, in a method, I need to retrieve the elements of contacts , however I am getting an EXC_BAD_ACCESS. Why is this? Why doesn't my contacts array keep the objects that I initialized it with in the beginning, and how do I fix this?

EDIT: The error comes when I select a NavigationBarItem which then triggers a method buttonWasPressed . In that method, I simply have the following:

-(void)buttonWasPressed:(id)sender {
    NSLog(@"button was pressed");
    if(contacts == nil)
       NSLog(@"contacts is nil!");

    NSLog(@"contacts = %@",contacts);
}

And I see "button was pressed" printed, but then there is an EXEC_BAD_ACCESS.

That code all looks good, nothing wrong there. I would guess you are over-releasing elsewhere. Turn on Zombies - add NSZombieEnabled to YES in the executable arguments and it will break on the line so you can see what object is being over-released.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM