当前位置: 动力学知识库 > 问答 > 编程问答 >

objective c - What does __weak do in this scenario

问题描述:

Class __weak *variable = preExistingObjectWithStrongReference;

If the above code is called, and a object with a strong reference is then pointed to by a new pointer 'variable', and the __weak attribute is assigned to it...

Does that simply mean that the reference count remains untouched? Or does it mean that the original object is now no longer strong referenced?

网友答案:

__weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.

This means that you can use variable safely as long as there's any other strong reference to the same object. In a certain sense you can think of it as the 'reference count remains untouched' as you said.

网友答案:

Neither; this means that the compiler will keep the reference alive as long as someone else points to it strongly. If there are no more strong references, and all of the objects that refer to your weak pointer are gone, the object is deallocated. Generally you only use weak on objects that you do not own. If you do own them (i.e it is something that "belongs" the the class) then strong is a better choice. A weak is essentially an unretained property, except the when the object is deallocated the weak pointer is automatically set to nil.

分享给朋友:
您可能感兴趣的文章:
随机阅读: