`
hunxiejun
  • 浏览: 1142429 次
文章分类
社区版块
存档分类
最新评论

Why are Objective-C delegates usually given the property assign instead of retain?

 
阅读更多

转自:http://stackoverflow.com/questions/918698/why-are-objective-c-delegates-usually-given-the-property-assign-instead-of-retai


问:

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

Directly from Scott's blog:

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

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?

Thanks!



答:

The reason that you avoid retaining delegates is that you need to avoid a retain loop (more commonly known as retain cycle):

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

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

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




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics