为什么 Objective-C 委托通常被赋予属性分配而不是保留? [英] Why are Objective-C delegates usually given the property assign instead of retain?

查看:18
本文介绍了为什么 Objective-C 委托通常被赋予属性分配而不是保留?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览由 Scott Stevenson 维护的精彩博客,我正在尝试理解一个基本的 Objective-C 概念,即为代表分配分配"属性与保留".请注意,两者在垃圾收集环境中是相同的.我最关心的是非基于 GC 的环境(例如:iPhone).

I'm surfing through the wonderful blog maintained by Scott Stevenson, and I'm trying to understand a fundamental Objective-C concept of assigning delegates the 'assign' property vs 'retain'. Note, the both are the same in a garbage collected environment. I'm mostly concerned with a non-GC based environment (eg: iPhone).

直接来自 Scott 的博客:

Directly from Scott's blog:

assign 关键字将生成一个 setter,它直接将值分配给实例变量,而不是复制或保留它.这最适用于 NSInteger 和 CGFloat 等原始类型,或者您不直接拥有的对象,例如代表."

"The assign keyword will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. This is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates."

您不直接拥有委​​托对象是什么意思?我通常会保留我的代表,因为如果我不希望他们陷入深渊,保留会为我解决这个问题.我通常将 UITableViewController 从其各自的数据源和委托中抽象出来.我也保留了那个特定的对象.我想确保它永远不会消失,所以我的 UITableView 总是有它的委托.

What does it mean that you don't directly own the delegate object? I typically retain my delegates, because if I don't want them to go away into the abyss, retain will take care of that for me. I usually abstract UITableViewController away from its respective dataSource and delegate also. I also retain that particular object. I want to make sure it never goes away so my UITableView always has its delegate around.

有人可以进一步解释我错在哪里/为什么错,这样我就可以理解 Objective-C 2.0 编程中使用委托而不是保留的分配属性的常见范例?

Can someone further explain where/why I'm wrong, so I can understand this common paradigm in Objective-C 2.0 programming of using the assign property on delegates instead of retain?

谢谢!

推荐答案

避免保留委托的原因是需要避免保留循环:

The reason that you avoid retaining delegates is that you need to avoid a retain cycle:

A 创造 BA 将自己设置为 B 的代表…A 被其所有者释放

A creates B A sets itself as B's delegate … A is released by its owner

如果 B 保留了 A,A 将不会被释放,因为 B 拥有 A,因此 A 的 dealloc 将永远不会被调用,导致 A 和 B 泄漏.

If B had retained A, A wouldn't be released, as B owns A, thus A's dealloc would never get called, causing both A and B to leak.

您不应该担心 A 会消失,因为它拥有 B 并因此在 dealloc 中摆脱它.

You shouldn't worry about A going away because it owns B and thus gets rid of it in dealloc.

这篇关于为什么 Objective-C 委托通常被赋予属性分配而不是保留?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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