4

我有一个视图控制器,当它完成时,我发布一个通知,并在另一个视图控制器中包含的子视图中添加为 oberserve。但是,当它尝试执行发布通知方法时,exec_bad_access 发生了。怎么了?代码是:

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__);
}

即使我摆脱了 userInfo,仍然无法访问。我在另一个新项目中创建了类似的情况,它工作正常。

4

2 回答 2

7

我没有意识到你正在处理 aUIView而不是 a UIViewController(应该更好地阅读你的问题)。我认为正在发生的事情是视图即使在被释放后也会收到通知。确保调用dealloc你的UIView并移除自己作为观察者:

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

另外,NSLog在 thatUIViewinitWithFrame方法中添加一个以查看它是否被多次调用。

这个问题非常相似:

ios 通知“死”对象

于 2013-04-14T02:37:50.303 回答
1

不确定这是否是原因,但是当您将视图添加到通知中心时,您的选择器是错误的:

selector:@selector(didSelectedBrandId::)

应该只有一个冒号。整行应该是:

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

两个冒号表示该方法接受两个参数,但它只接受一个。

于 2013-04-14T02:35:40.427 回答