Paranoia about someone else stealing delegate status


#1

Several times in the book we’re told we should remove ourselves as the delate of an object in dealloc or viewWillDisappear: or similar.

I was wondering if it’s worth me worrying about another object setting itself as the delegate. In other words, to be safe should I ask the delegating object for its delegate and compare that to self before setting the delegate to nil?

On page 119, for example, I’d write this:

  • (void)viewWillDisappear:(BOOL)animated
    {
    [super viewWillDisappear];
    if ([[UIAccelerometer sharedAccelerometer] delegate] == self) {
    [[UIAccelerometer sharedAccelerometer] setDelegate:nil];
    }
    }

Am I wasting my time?


#2

Yeah, in practice, you don’t see this problem very often. Most of the time, an object only ever has one delegate and its most likely a controller object that owns the delegating object anyway.

In rare cases, an object might have more than one delegate over time. (For example, one way to implement a tree-based XML parser requires that you change the delegate of the event-based NSXMLParser as you pop into entries.) Most of the time, though, you have one controller object handling the changing of this delegate.

It is only the case of singletons that are accessible by everyone that have a delegate where this could possibly get tricky. The accelerometer is such a case. It doesn’t hurt to check before nil’ing the delegate, so you can do it if you are worried about it. However, most of the time, the delegate changes hands so few times it is pretty easy to just know what is going on and not worry about it.