Search code examples
iphonememory-managementnsurlconnectionnszombie

How to handle NSZombies in an asynchronous NSURLConnection?


I'm currently asynchronously using NSURLConnection with several UIViews (every view handles NSURLConnection as delegate). The problem I have is when user switches views too fast and the delegate becomes NSZombie the app crashes - that is NSURLConnection doesn't have living delegate anymore. So, the first question is if there's a way to circumvent this?

The second question is simple - how do I handle NSZombie? Simple if(myObject != nil).. doesn't work at all.


Solution

  • You need to cancel the NSURLConnection before you dispose it's delegate. Simply keep a reference to the NSURLConnection in your UIView that acts as a delegate and call [urlConnection cancel].

    After you release a message you need to set your pointer to it to nil if you continue using that pointer. As an example:

    id myObject = [[SomeObject alloc] init];
    
    /* Some code */
    
    [myObject release];
    myObject = nil;
    
    /* Some more code */
    
    if (myObject != nil) {
       [myObject doSomething];
    }
    

    Notice however that it is valid to send a message to nil so you don't need to safe guard the message sending. It simply won't have any effect if myObject == nil.