只读插座?
假设我有课。我想通过以下方式声明一个属性:
- 从类外部,如果以编程方式访问,它应该是只读的;
- 应该可以使用插座从 Interface Builder 设置值;
- (从类内部它应该是可写的,但我知道该怎么做)。
我想出的“解决方案”是编写一个一次性的setter:
- (void) setA: (ClassA *)a {
if (aHaveBeenSet)
return;
else {
// do what a setter have to do
aHaveBeenSet == YES;
}
}
但是这个setter仍然可以从代码中调用(尽管只有效一次),所以它不完全是一个解决方案。
另一种方法是将 ivar 标记为 IBOutlet 并使属性 readonly
如下所示:
@interface MyClass : NSObject {
IBOutlet ClassA *a;
}
@property (readonly) ClassA *a;
@end
但根据 这个答案,这是一种糟糕的风格,并且使内存管理不清楚。
有什么想法吗?
Let's say I have a class. I would like to declare a property in the following way:
- From outside of the class it should be read-only if accessed programmatically;
- It should be possible to set the value from the Interface Builder using an outlet;
- (From inside the class it should be writable, but I know how to do it).
The "solution" I came up with is to write a one-time setter:
- (void) setA: (ClassA *)a {
if (aHaveBeenSet)
return;
else {
// do what a setter have to do
aHaveBeenSet == YES;
}
}
But this setter still can be called from the code (though only once in effect), so it's not quite a solution.
Another way is to mark the ivar as IBOutlet and make the property readonly
like this:
@interface MyClass : NSObject {
IBOutlet ClassA *a;
}
@property (readonly) ClassA *a;
@end
But according to this answer, it's a poor style and makes memory management unclear.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我错了,有人会纠正我,但我认为 NIB 加载机制仅在运行时实例化 .nib 文件时检查 setter 方法。因此,这意味着您可以将公共属性声明为只读,但在 .m 文件中写入“私有”设置器:
Someone correct me if I'm wrong, but I think the NIB loading mechanism checks for a setter method only when instantiating a .nib file at runtime. So that means you could declare your public property as readonly but write a "private" setter in your .m file: