0

Possible Duplicate:
In dealloc method set any delegate to nil is needed or not needed

In ARC if class Foo owns an ivar and that ivar's delegate is set to Foo is it always a good safety precaution to set the ivar's delegate to nil in dealloc or is this precaution only used in some cases?

Community
  • 1
  • 1
stumped
  • 3,235
  • 7
  • 43
  • 76
  • it is good practice to set the delegate to nil. but if you declare the delegate is "weak" then it does not maintain a retain count, and therefore it is not required to set to nil because arc will not do anything special with it anyways. The reason to set it nil, is so calling it later will not result in any weird behavior. – The Lazy Coder Aug 13 '12 at 22:35

2 Answers2

0

It depends on the ivar. If Foo owns it “exclusively” and the ivar is not available to other classes, then there is no need to do _ivar.delegate = nil; in dealloc. But if the object is intended to be used in other classes as well, you would better to set the delegate to nil. However, this is very rare situation in Cocoa development.

Another approach mentioned in the answers is to always be safe and set the delegate to nil. But I would not recommend this. Sometimes, by leaving the delegate reference you may find a leaked object which tries to contact its “dead” delegate which owned it.

Vadim
  • 9,383
  • 7
  • 36
  • 58
0

Yes. Even thou most delegates are not retained (except on some time-lived classes such as CAAnimation and NSURLConnection), I have encountered circumstances (most specifically, using NSFetchedResultsController) where an object is trying to access a dead delegate. Delegates should be unsafe_unretained, so they should be nil when your object is deallocated, therefore making it redundant to eliminate the delegate on the dealloc method, but looking at the NSFetchedResultsController case, better be safe than sorry.

J2theC
  • 4,412
  • 1
  • 12
  • 14
  • You've got that swapped around. `__unsafe_unretained` doesn't nil out pointers, `weak` does. If you've been declaring everything `__unsafe_unretained` thinking it's nilling things out, that's probably why you're seeing this behaviour. – Jim Aug 13 '12 at 22:35
  • Thanks for the clarification. However the places were i had those problems i did not declare those delegates. – J2theC Aug 13 '12 at 22:40