0

重複の可能性:
dealloc メソッドでは、デリゲートを nil に設定する必要があるか、または必要ない

ARC では、クラスFooが ivar を所有し、その ivar のデリゲートが設定されている場合、ivar のデリゲートを設定するFooことは常に適切な安全対策ですかnildeallocそれともこの予防策は場合によってのみ使用されますか?

4

2 に答える 2

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.

于 2012-08-13T22:06:09.080 に答える
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.

于 2012-08-13T22:07:32.123 に答える