ARC では、クラスFoo
が ivar を所有し、その ivar のデリゲートが設定されている場合、ivar のデリゲートを設定するFoo
ことは常に適切な安全対策ですかnil
、dealloc
それともこの予防策は場合によってのみ使用されますか?
2 に答える
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.
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.