Why does a declared property use both retain and readonly?

亡梦爱人 提交于 2019-12-03 03:47:48

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/1933489/why-does-a-declared-property-use-both-retain-and-readonly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!