iOS check if delegate exists before call method

10,216

Try putting this code on dealloc section.

imageStore.delegate = nil;
imageStore = nil;

In the same way the if clause is not necessary because any call to an nil object is ignored by the application, so if you have something like this:

id delegate = nil;    
[delegate callAnyMethod];

has no effect in your application behavior, in other hand if the call of the method delegate is optional you should asure that delegate responds to selector, something like this should do the trick:

if([delegate conformsToProtocol:@protocol(yourProtocolName)] && [delegate respondsToSelector:@selector(imageStoreDidGetNewImage:url:)]) {
       [delegate imageStoreDidGetNewImage:imageStore url:url];
}

Cheers!

Share:
10,216
Vitaly Baev
Author by

Vitaly Baev

Updated on June 04, 2022

Comments

  • Vitaly Baev
    Vitaly Baev about 2 years

    I write iOS app and use imageStore library to lazy load images and cache them in memory. (https://github.com/psychs/imagestore)

    On ViewController I create imagestore instance:

    imageStore = [ImageStore new];
    imageStore.delegate = self;
    

    When image loaded successfuly, imagestore call delegate method

    - (void)imageStoreDidGetNewImage:(ImageStore*)sender url:(NSString*)url
    

    that doing reloadData on tableview to redraw cells. All works good. But there is the problem: if ViewController didUnload (go back in navigation controller) and image loaded, application finish with crash, because imagestore call method of unloaded ViewController.

    I try to do following: 1) in ViewController I place this code in viewDidUnload section:

    imageStore.delegate = nil;
    imageStore = nil;
    

    2) In imageStore I added checking for nil:

    if(delegate != nil) {
      ...call delegate method
    }
    

    It works, but periodically app crash anyway.