I know the definition of unsafe_unretained
.
So i don't expect anyone to write its definition.
I want to know its use with example, and how it works with memory management.
unsafe_unretained
only exists in ARC (Automatic Reference Counting). It works like assign
in MRC (Manual Reference Counting). These properties won't be retained. Usually, you'd want to use such properties for delegates, because they don't need an owner which retains them.
weak
properties are like unsafe_unretained
, except that they work a bit smarter. When the object assigned to the property is released, a weak reference automatically becomes nil
, to avoid crashes when sending messages to that object (its memory address).
unsafe_unretained
properties don't do this. They will always hold on to the memory address (unless you manually change it) assigned to it, regardless of the object associated to that address. Weak references can prevent crashes in such a case, but the result still won't be as expected. If your code is organized and well-written, this shouldn't happen.
So why would you use unsafe_unretained
instead of weak
? Weak references are only available on iOS 5 and higher, so if you're building an ARC app targeting iOS 4, you need to use unsafe_unretained
properties. And again, sending messages to a released property isn't anything you want to have in any code. If your code is well organized then you shouldn't have any problems with this.
Previously to ARC, one might specify a delegate or other reference-to-parent property as assign
to prevent retain cycles. With the introduction of ARC and the newer compilers you would instead use unsafe_unretained
.
So you use it any time you do not need ownership of the reference, and when you don't need or want to use the new weak
reference type (which nulls out the reference when it is deallocated).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With