由于PostNotification导致的EXC_BAD_ACCESS

Sag*_*... 3 iphone ipad

我正面临一个关于一个模块的问题让我清楚了解相同的流程.

我有一个定制的UITableviewCell.

当我收到一些新信息时,我发布了一条通知

[[NSNotificationCenter defaultCenter] postNotificationName:KGotSomething object:nil userInfo:message];
Run Code Online (Sandbox Code Playgroud)

鉴于我在维护表格,我正在启动一个自定义单元格

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell= [[CustomCell alloc] initWithFrame: reuseIdentifier:identifier document:doc];
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

现在在customcell.mm

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier 
{
[[NSNotificationCenter defaultCenter] addObserver:self 
                 selector:@selector(GotSomething:) 
                         name:KGotSomething 
                        object:nil];
}
Run Code Online (Sandbox Code Playgroud)

并在dealloc

- (void)dealloc 
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                    name:KGotSomething 
                       object:nil];
}
Run Code Online (Sandbox Code Playgroud)

现在我的应用程序由于此通知而崩溃,并且永远不会调用dealloc.

你们可以帮助我,如何让这个工作或者我在这里做错什么......

谢谢,

萨加尔

Lau*_*ble 6

initWithFrame:reuseIdentifier:dealloc方法都不完整.这是故意的吗?

initWithFrame:reuseIdentifier: 应该包含对super的调用:

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier 
{
    self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self 
                 selector:@selector(GotSomething:) 
                         name:KGotSomething 
                        object:nil];
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

而且dealloc:

- (void)dealloc 
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                    name:KGotSomething 
                       object:nil];
    [super dealloc];
}
Run Code Online (Sandbox Code Playgroud)

更新

单元格创建后不会自动释放.因此,细胞正在泄漏,永远不会被解除分配.代码应该是:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell= [[CustomCell alloc] initWithFrame: reuseIdentifier:identifier document:doc];
    return [cell autorelease];
}
Run Code Online (Sandbox Code Playgroud)