简体   繁体   中英

iOS check if delegate exists before call method

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.

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!

It works, but periodically app crash anyway.

That's a contradiction. There are two possibilities:

  1. Your fix worked, and the app is crashing for some other reason.

  2. Your fix did not work, the app continues to crash for the same reason it was crashing before.

It's hard to know what's wrong without knowing which of these two possibilities is in fact happening. Look at the error message and the evidence from the crash, such as the stack crawl. Why is the app crashing? Does it try to dereference the delegate property somewhere without checking it first? Does it depend on the delegate doing something, so that if the delegate no longer exists that thing doesn't get done and that in turn leads to a crash? These are the kinds of things I'd look for, but again the most important thing is to start with the evidence you have and follow your nose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM