What is the use of unsafe_unretained attribute?

后端 未结 3 1043
忘了有多久
忘了有多久 2021-02-05 18:31

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 wor

3条回答
  •  野的像风
    2021-02-05 19:09

    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.

提交回复
热议问题