开发者

UIViewController is popped from view stack and NSURLConnection crashes the application

开发者 https://www.devze.com 2022-12-31 14:08 出处:网络
I am pushing a UIViewController onto a UINavigationController.This view controller immediately starts a download of an xml feed and then parses it.However, if you hit the back button before it is done

I am pushing a UIViewController onto a UINavigationController. This view controller immediately starts a download of an xml feed and then parses it. However, if you hit the back button before it is done downloading, and crashes with EXC_BAD_ACCESS. The line that is crashing it is in parserDidEndDocument and is this line:

if (self.delegate && [self.delegate conformsToProtocol:@protocol(ModelDelegate)]) [self.delegate modelDidFinishParsing:self];

I assume it is crashing because it is trying to access self.delegate which is not assigned anymore. How do I get aroun开发者_如何学运维d this?

Also, I would release the model object in the modelDidFinishParsing method. How would I release this model if it never reaches this method.


I set up objects to handle my downloads (and other asynchronous or long running tasks) in the AppDelegate, then trigger them as required from various controllers. That way they are owned and have persistence through the life of the application.

The best way to do this is to pass them to the viewControllers that will need them (rather than the viewController "expecting" the appDelegate to have such and such an object ready and waiting) - dependency injection.

These objects update my model in some way when they finish and if I need to, I use NSNotifications to announce they are done. This isolates me from the mess I used to get into trying to cancel or swap delegates in viewWillDisappear etc to avoid the kind of issues you are running into.


The reason your app is crashing is probably because NSURLConnection retains its delegate (so it can call back to it reliably) but objects that this delegate has weak references to have been deallocated.

Ie, in your case what self.delegate points to has probably been deallocated when the view controller is popped but the delegate property has not been cleared (set to nil).

The solution to your problem is to clear (nil) self.delegate at the appropriate time when the UIViewController subclass is being popped off the navigation stack.

Note: retaining delegates is not usual behaviour for Cocoa classes. In situations where it happens contrary to standard practice it is documented (see the NSURLConnection docs).

0

精彩评论

暂无评论...
验证码 换一张
取 消