Search code examples
iphoneuiviewviewcontrollernsnotificationcenter

NSNotificationCenter postNotificationName exec_badaccess


I have a view controller, when it's dissming with completion, I post a notfication, and in a subview which contained in another view controller, has added as a oberserve. But, when it tries to execute post notificaiton methode, exec_bad_access happend. what's wrong? The codes are:

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 the userInfo, still bad access. I created a similar situation in another new project, it works fine.


Solution

  • I didn't realize that you were dealing with a UIView and not a UIViewController (should have read your question better). I think what is happening is that the View is receiving notifications even after being released. Make sure to call dealloc in your UIView and remove itself as an observer:

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

    Also, put an NSLog in that UIView's initWithFrame method to see if it is being called more than once.

    This question is very similar:

    ios notifications to "dead" objects