NSNotificationCenter postNotificationName exec_badaccess

I have a view controller, when it parses with completion, I send a notification, and in the subheading, which is contained in another view controller, is added as a talisman. But, when he tries to execute the post notificaiton method, exec_bad_access happens. what's wrong? Codes:

BrandListByIdViewController.m - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSNumber *bid = self.brands[indexPath.row][@"id"]; [self dismissViewControllerAnimated:YES completion:^{ [[NSNotificationCenter defaultCenter] postNotificationName:@"SelectedBrandId" object:nil]; }]; } SearchNewProduct.h @interface SearchNewProduct : UIView @end SearchNewProduct.m - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSelectedBrandId::) name:@"SelectedBrandId" object:nil]; } } - (void)didSelectedBrandId:(NSNotification *)notif{ NSLog(@"%s", __PRETTY_FUNCTION__); } 

Even I get rid of userInfo, still bad access. I created a similar situation in another new project, it works great.

+4
source share
2 answers

I did not understand that you are dealing with a UIView , not a UIViewController (it is better to read your question). I think it happens that the View receives notifications even after exiting. Be sure to call dealloc in the UIView and remove yourself as an observer:

 - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } 

Also, put the NSLog in this UIView initWithFrame method to see if it is called more than once.

This question is very similar:

ios notifications on "dead" Objects

+7
source

Not sure if this is the reason, but when you add your view to the notification center, your selector is wrong:

 selector:@selector(didSelectedBrandId::) 

There must be only one colon. The whole line should be:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSelectedBrandId:) name:@"SelectedBrandId" object:nil]; 

Two colons indicate that the method takes two arguments, but it takes only one.

+1
source

All Articles