Avoiding EXC_BAD_ACCESS when using the delegate pattern

Posted by Kenny Winker on Stack Overflow See other posts from Stack Overflow or by Kenny Winker
Published on 2010-04-21T03:44:29Z Indexed on 2010/04/21 3:53 UTC
Read the original article Hit count: 416

A have a view controller, and it creates a "downloader" object, which has a reference to the view controller (as a delegate). The downloader calls back the view controller if it successfully downloads the item. This works fine as long as you stay on the view, but if you navigate away before the download is complete I get EXC_BAD_ACCESS. I understand why this is happening, but is there any way to check if an object is still allocated? I tried to test using delegate != nil, and [delegate respondsToSelector:], but it chokes.

if (!self.delegate || ![self.delegate respondsToSelector:@selector(downloadComplete:)]) {
  // delegate is gone, go away quietly
        [self autorelease];
        return;
    }
else {
  // delegate is still around
  [self.delegate downloadComplete:result];
}

I know I could,

a) have the downloader objects retain the view controller

b) keep an array of downloaders in the view controller, and set their delegate values to nil when I deallocate the view controller.

But I wonder if there is an easier way, where I just test if the delegate address contains a valid object?

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about memory-management