Why does a declared property use both retain and readonly?

本文探讨了Objective-C中在属性声明中同时使用retain和readonly的逻辑与用意,解释了这种组合在内存管理、属性访问控制及代码模式上的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I've noticed that some of Apple's examples include both a retain and readonly modifier on properties. What's the point of including retain if no setter gets generated when we're using the readonly modifier?

Example: @property (retain, readonly) NSString *title; from the AnimatedTableView sample.




I've noticed that some of Apple's examples include both a retain and readonly modifier on properties. What's the point of including retain if no setter gets generated when we're using the readonly modifier?

Example: @property (retain, readonly) NSString *title; from the AnimatedTableView sample.

share improve this question
 

2 Answers

up vote 17 down vote accepted

You can include a second, private readwrite declaration in a class extension. The memory management scheme for all references needs to match IIRC, so you get silliness like "readonly, retain".

share improve this answer
 
3 
It isn't entirely silly; the matrix of modifiers vs. @synthesize is such that the getter's code can change. Trying to suss out exactly which modifiers should be able to be added vs. which should #warn would rife with minutia and hard to ultimately understand. Better to simply go with "must be same except readonly->readwrite". –   bbum  Dec 19 '09 at 19:28
 
Figured i should expand on my comment.... –   bbum  Feb 23 '10 at 22:20

Or, more specifically, (readonly, retain) enables a pattern like this:

Foo.h:

@interface StuffHolder:NSObject
@property(readonly, retain) MyStuff *stuff;
@end

Foo.m:

@interface StuffHolder()
@property(readwrite, retain) MyStuff *stuff;
@end

@implementation StuffHolder
@synthesize stuff;
@end

The end result is a property that is publicly readonly while being readwrite within the implementation and for whom both setter and getter are synthesized automatically by the compiler.

A warning could be generated in the case of no (readwrite, retain) override in the class extension -- something akin to statement without an effect -- but it would be more confusing than beneficial. There are also a whole slew of different edge cases across the combinations that would equally warrant a warning, but don't really indicate an actual problem. The decision was made to largely accept the various patterns without complaint for simplicity's sake (since they aren't correctness issues).



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值