Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of unsafe_unretained attribute?

Tags:

ios

iphone

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.

like image 689
liza Avatar asked Apr 12 '13 09:04

liza


2 Answers

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.

like image 72
JonasG Avatar answered Nov 11 '22 12:11

JonasG


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).

like image 39
Mike Weller Avatar answered Nov 11 '22 11:11

Mike Weller