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?
No, you can’t (usefully) “test if an address contains a valid object”. Even if you were able to grub around inside the internals of the memory allocation system and determine that your address points to a valid object, that would not necessarily mean that it was the same object that you were previously referring to: the object could have been deallocated and another object created at the same memory address.
Retaining the delegate is the usual way to solve this. Your option (b) breaks object encapsulation, and might have thread-safety issues.