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

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

问题描述

我正在浏览由Scott Stevenson维护的精彩博客,我试图理解一个基本的Objective-C概念,即分配委托的assign属性和retain。注意,这两者在垃圾收集环境中是相同的。我主要关心一个非基于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远离其各自的dataSource和委托也。我也保留那个特定的对象。我想确保它永远不会消失,所以我的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.

有人可以进一步解释在哪里/为什么我错了,所以我可以理解这

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创建B
A将自己设置为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委托通常给予属性assign而不是retain?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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