unsafe_unretained属性有什么用? [英] What is the use of unsafe_unretained attribute?

查看:116
本文介绍了unsafe_unretained属性有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 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 仅存在于ARC中(自动引用计数)。它的工作方式类似于MRC(手动参考计数)中的 assign 。这些属性不会被保留。通常,您希望将这些属性用于代理,因为它们不需要保留它们的所有者。

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.

属性类似于 unsafe_unretained ,除了它们更聪明一些。当释放分配给属性的对象时,弱引用会自动变为 nil ,以避免在向该对象发送消息(其内存地址)时发生崩溃。

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 属性不会这样做。无论与该地址关联的对象如何,它们都将始终保持分配给它的内存地址(除非您手动更改它)。在这种情况下,弱引用可以防止崩溃,但结果仍然不会如预期的那样。如果您的代码是有条理的并且写得很好,那么这不应该发生。

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.

那你为什么要使用 unsafe_unretained 而不是?弱引用仅适用于iOS 5及更高版本,因此如果您要构建面向iOS 4的ARC应用,则需要使用 unsafe_unretained 属性。再次,向已发布的属性发送消息并不是您想要在任何代码中拥有的任何内容。如果您的代码组织良好,那么您应该没有任何问题。

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.

这篇关于unsafe_unretained属性有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆