问题描述:

I pass an object from a xviewController to yviewController via segue,

The object obj is initalized at xviewController as a strong property.

I pass the object to yviewController's property which is a pointer of the same class.

When a viewcontroller dissappears, is it still pointing that address or does it just sets it to nil.

The question is, should i define this second pointer as a weak pointer or a strong ?

网友答案:

The correct answer is it depends.

First you have to understand the difference between strong and weak.

Making it short, a strong reference owns the object you are referencing with this property. What means that the compiler will make sure that this object will not be removed from memory while there is a strong reference to it. If you have two objects pointing strongly to another, and one is removed, the second one will still have this object, because it owns it.

A weak reference basically means that the objected is not owned, it's ownership is still from who has the strong reference, so in case the strong reference stop existing, the weak will be then pointing to nil. So repeating, A has a strong reference to X, B has a weak reference to X, if A removes this reference, B will lose it too..

So.. back to your question, weak or strong in the second View controller, it will depend.. is there a possibility that the first view controller will destroy the object while the second view controller is visible? If this happen you want to keep your copy of the object? If booth yes, put it strong.

If there is no way that the first reference is destroyed, or you want to reflect updates in the first object (updates keeping the instance) in the second view controller, a weak reference is enough.

网友答案:

If I understand you correctly then it should be strong (the default). When the second view controller is destroyed ARC will assign the object pointer to nil removing one reference, however you will still want to reference the object in the first view controller.

相关阅读:
Top