简体   繁体   中英

addObject in NSMutableArray error

I am trying to show or hide buttons for actions you can take for a contact depending on whether certain data is present, ie there is a phone number or facebookid. The following code compiles but then crashes on the buttonsToHide line.

NSMutableArray *buttonsToShow = [NSMutableArray arrayWithObjects:self.facebookButton,self.callButton, self.smsButton, self.emailButton, self.deleteButton, nil];   
NSMutableArray *buttonsToHide = [NSMutableArray array];

NSLog(@"Facbook id is:%@",self.contact.facebookID);

if (self.contact.facebookID == nil) {
    [buttonsToShow removeObject:self.facebookButton];
    //Following line crashes and shows up in green
    [buttonsToHide addObject:self.facebookButton];
}

Would appreciate any suggestions on what is causing it to crash.

It's almost certainly isn't crashing on the second array allocation, but on the first, and that crash is almost certainly caused by one the elements in the initialization being nil.

NSMutableArray *buttonsToShow;
if (self.facebookButton && self.callButton && self.smsButton && self.emailButton && self.deleteButton) {
    buttonsToShow = [NSMutableArray arrayWithObjects:self.facebookButton,self.callButton, self.smsButton, self.emailButton, self.deleteButton, nil];  
} else {
    buttonsToShow = [NSMutableArray array];
    NSLog(@"didn't initialize the array because placing nil objects in an array causes a crash");
} 

Are those buttons IBOutlets? Possibly not hooked up?

Seems like self.facebookButton is nil. Verify if they are initialized if they are code programmatically or connected to the views in the interface builder.

The following code will avoid the crash. But you may want to check why self.facebookButton is nil and fix

if (self.contact.facebookID == nil && self.facebookButton) {
    [buttonsToShow removeObject:self.facebookButton];
    //Following line crashes and shows up in green
    [buttonsToHide addObject:self.facebookButton];
}

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