Search code examples
iosuiviewcontrollerdelegatescrashviewdidload

what happens if delegate doesnot exist anymore?


I came around a interesting issue while working on my app. Imagine the scenerio where

  • There exist one object, Lets call it A.
  • A, then creates an object(B) of some delegation based class, say NSURLConnection.
  • A assigned itself as delegate of B, provided A has implemented all the required delegate methods.
  • A asks B to start its processing. In our example i.e. fetching data from some server.
  • As soon as B finished fetching data, it will call some specified method of A.

In the last step, suppose while calling the methods of A, B finds that the A object doesnt exist anymore. Then what happens???

I'm not sure but does it cause crash?

If yes, then please suggest me how to avoid the situation.

In my case I assigned the viewcontroller as delegate of some object, say X in viewDidLoad method. There are cases when viewcontroller get destroyed before X calls the delegate methods defined in the viewcontroller.

  • If assigning X's delegate to nil solves the problem. Then where should i do that.

In short, which method is called only once while unloading phase of view controller likewise viewDidLoad in its loading phase.


Solution

  • Checking against a valid delegate object should be sufficient enough.

    if (delegate)
       [delegate method];