0

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.

Harshit Gupta
  • 1,200
  • 12
  • 27

3 Answers3

1

You should not reach a situation where one object holds a reference to another object which may be deallocated somewhere else without the owner object being notified.

Either when deallocating object A notify object B (by making member a nill in object B for example) or modify your design/flow to never allow A to be deallocated before B finishes (e.g. retain A when assigning as a delegate in B if possible)

giorashc
  • 13,691
  • 3
  • 35
  • 71
1

The best way to achieve this kind of communication between classes (where class A could be deallocated at any time) is listening to NSNotifications.
As you stated , using weak(assign) delegates is dangerous and requires extra thought.
Using strong delegates could as well create a memory bloat (why should we retain a view controller so long after popping it from the view anyway?).

For more on NSNotificationCenter and notifications , you can find a lot of info in the SDK docs.. for specific questions, you know where to ask..

Nir Golan
  • 1,336
  • 10
  • 24
0

Checking against a valid delegate object should be sufficient enough.

if (delegate)
   [delegate method];
Lefteris
  • 14,550
  • 2
  • 56
  • 95
  • specifically speaking about the NSURLConnection class, did you mean it will not look for the viewcontroller or viewcontroller's " - (void)connectionDidFinishLoading:(NSURLConnection *)connection" method, if view controller doesn't exist any more? – Harshit Gupta Oct 18 '12 at 12:12
  • If the delegate is deallocated , then "delegate" will point to some garbage pointer.. I'd (and the MVC design pattern would) prefer using notifications for this kind of flow. – Nir Golan Oct 18 '12 at 12:53