需要在解除分配之前删除Observer,但ARC禁止覆盖解除分配



我有一个类,RA_CustomCell : UITableViewCell。该类的一些实例注册为另一类RA_LocationSingleton中的变量currentLocation的观测器。

RA_自定义单元格.m

-(void)awakeFromNib
{
    [self registerAsListener]
}
-(void)registerAsListener
{
    if ([self.reuseIdentifier isEqualToString:@"locationcell1"])
    {
        [[RA_LocationSingleton locationSingleton]
               addObserver:self
                forKeyPath:@"currentLocation"
                   options:NSKeyValueObservingOptionNew
                   context:nil];
    }
}

然而,当用户向后导航时,这些单元格会自然地被释放。问题是,当currentLocation变量更新自己时,我会得到以下崩溃错误:

*** -[RA_CustomCell retain]: message sent to deallocated instance 0x9bd9890

不幸的是,我无法覆盖-dealloc,因为我正在使用ARC,并且键入[super dealloc]会产生以下警报:

ARC forbids explicit message send of 'dealloc'

我的问题是,我应该如何最好地管理我的位置听众,以避免这种崩溃?

只需使用dealloc而不调用[super dealloc]:

- (void)dealloc {
   [[RA_LocationSingleton locationSingleton] removeObserver:self
                                                 forKeyPath:@"currentLocation"
                                                    context:nil];
}

从苹果文档过渡到ARC发布说明,ARC实施新规则:

ARC中的自定义解除锁定方法不需要调用[super-dealloc](它实际上会导致编译器错误)。链接到super由编译器自动执行。

您可以覆盖dealloc,只是[super dealloc]会自动为您调用。

它在这里的苹果文档中进行了解释

"ARC中的自定义dealloc方法不需要调用[super dealloc](这实际上会导致编译器错误)。链接到super是自动的,并由编译器强制执行。"

最新更新