Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 730
yong ho Avatar asked Feb 16 '23 19:02

yong ho


1 Answers

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

like image 151
LJ Wilson Avatar answered Mar 05 '23 12:03

LJ Wilson