为什么声明的属性同时使用retain和readonly?

发布于 2024-08-15 08:40:10 字数 251 浏览 12 评论 0原文

我注意到 Apple 的一些示例在属性上同时包含 retainreadonly 修饰符。如果我们使用 readonly 修饰符时没有生成 setter,那么包含 retain 有何意义?

示例:来自 AnimatedTableView 示例的 @property (retain, readonly) NSString *title;

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

药祭#氼 2024-08-22 08:40:10

或者,更具体地说, (readonly, keep) 启用如下模式:

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

最终结果是一个公开只读的属性,同时在实现中进行读写,并且 setter 和 getter 都会自动合成由编译器。

如果类扩展中没有(读写、保留)重写,可能会生成警告 - 类似于没有效果的语句 - 但效果会更好混乱多于有益。组合中还存在大量不同的边缘情况,这些情况同样值得发出警告,但并不真正表明存在实际问题。为了简单起见,我们决定在很大程度上接受各种模式,而不会抱怨(因为它们不是正确性问题)。

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

有深☉意 2024-08-22 08:40:10

您可以在类扩展中包含第二个私有读写声明。所有引用的内存管理方案都需要匹配 IIRC,因此您会得到诸如“只读,保留”之类的愚蠢内容。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文