Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS check if delegate exists before call method

Tags:

ios

iphone

crash

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.

like image 264
Vitaly Baev Avatar asked Nov 02 '11 06:11

Vitaly Baev


1 Answers

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!

like image 139
D33pN16h7 Avatar answered Oct 19 '22 04:10

D33pN16h7