Search code examples
iosobjective-clocationobserver-patterndealloc

Need to removeObserver before deallocation, but ARC forbids overriding dealloc


I've got a class, RA_CustomCell : UITableViewCell. Some instances of this class register to be observers of a variable currentLocation in another class RA_LocationSingleton.

RA_CustomCell.m

-(void)awakeFromNib
{
    [self registerAsListener]
}

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

However, these cells get deallocated naturally when the user navigates backwards. The problem is that when the currentLocation variable updates itself, I get the following crash error:

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

Unfortunately, I cannot override -dealloc because I am using ARC, and typing [super dealloc] produces the following alert:

ARC forbids explicit message send of 'dealloc'

My question is, how best should I manage my location listeners to avoid this kind of crash?


Solution

  • Just use dealloc without calling [super dealloc]:

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

    From the apple doc on Transitioning to ARC Release Notes, ARC Enforces New Rules:

    Custom dealloc methods in ARC do not require a call to [super dealloc] (it actually results in a compiler error). The chaining to super is automated and enforced by the compiler.