开发者

Can't assign delegate

开发者 https://www.devze.com 2023-02-11 03:38 出处:网络
I have two view controllers. The flow between them is as follows: VC1 creates VC2 and sets VC2.delegate to self. In VC2, the delegate property is assigned, not retained. When VC2 is displayed, VC1 is

I have two view controllers. The flow between them is as follows:

VC1 creates VC2 and sets VC2.delegate to self. In VC2, the delegate property is assigned, not retained. When VC2 is displayed, VC1 is dealloced, thus the delegate property of VC2 is a zombie object. VC2 is supposed to retrieve some data from a server and call the delegate with that data, but that won't work since the delegate was already deallocated.

My question: should I just retain the delegate in VC2 and release it in the dealloc method of VC2, or am I missing something fundamental here since the delegate pattern in iPhone 开发者_运维百科suggests assigning delegates and not retaining them.

Thanks!


You should set the delegate to nil before you dealloc VC1. VC2 should not have any knowledge of VC1 (only what protocol it is conform to).

With retaining VC1 in VC2, VC1 will probably never get deallocated. (only with a really ugly structure of code)

It is obvious that when the object VC1 deallocated that is has to do its cleanup, so it has to set the delegate to nil.

Back to your question: you should never retain a delegate. Its just code construction.

0

精彩评论

暂无评论...
验证码 换一张
取 消