Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you set the delegate to nil in the class using the delegate or in the class itself

If class A is using class B and class A is class B's delegate, is it ok if the delegate is set to nil in class B's dealloc? I have seen code usually resetting the delegate to nil inside class A's dealloc but wasn't sure the real difference doing it one way or the other.

e.g. This is the usual way:

// somewhere in class A

- (void) someFunc {
  self.b = [[B alloc] init];
  self.b.delegate = self;
}

- (void) dealloc {
  self.b.delegate = nil;
  [self.b release];
}
like image 331
Boon Avatar asked Jul 01 '09 23:07

Boon


2 Answers

Yes, you should set the classB's delegate property to nil in classA's dealloc.

It's not a memory management issue, because delegate properties should be marked assign, not retain, to avoid retain cycles (otherwise the dealloc will never be called). The issue is that otherwise classB might message classA after it has been released.

For example, if classB has a delagate call to say "being hidden", and classB is released just after classA, it would message the already dealloc'ed classA causing a crash.

And remember, you can't always guarentee the dealloc order, especial if they are autoreleased.

So yes, nil out the delegate property in classA's dealloc.

like image 101
Peter N Lewis Avatar answered Sep 24 '22 03:09

Peter N Lewis


As far as I know, its best practice to (assign) a delegate, such that you avoid circular references on retain counts for situations just like this. If you've set up the property properly, ie:

@property (assign) id<BDelegate> delegate;

You shouldn't have to perform any memory management in the dealloc, as the retain count is not bumped when you call self.b.delegate = self; -- unlike using (retain) or (copy)

Make sense? It would be fine to set the delegate to nil, but whats the point?

like image 38
Josh Avatar answered Sep 22 '22 03:09

Josh