如何声明由可变类型支持的不可变属性?
我想声明一个公共不可变属性:
@interface Foo
@property(strong, readonly) NSSet *items;
@end
……在实现文件中以可变类型为后盾:
@interface Foo (/* private interface*/)
@property(strong) NSMutableSet *items;
@end
@implementation
@synthesize items;
@end
我想要的是实现中的一个可变集合,当从外部访问时,该集合会被转换为不可变集合。 (我不在乎调用者可以将实例强制转换回 NSMutableSet 并破坏封装。我住在一个安静、体面的小镇,这样的事情不会发生。)
现在我的编译器将实现中的属性为 NSSet
。我知道有很多方法可以让它工作,例如使用自定义 getter,但是有没有一种方法可以简单地使用声明的属性来完成它?
I’d like to declare a public immutable property:
@interface Foo
@property(strong, readonly) NSSet *items;
@end
…backed with a mutable type in the implementation file:
@interface Foo (/* private interface*/)
@property(strong) NSMutableSet *items;
@end
@implementation
@synthesize items;
@end
What I want is a mutable collection in the implementation that gets cast into an immutable one when accessed from the outside. (I don’t care that the caller can cast the instance back to NSMutableSet
and break the encapsulation. I live in a quiet, decent town where such things don’t happen.)
Right now my compiler treats the property as NSSet
inside the implementation. I know there are many ways to get it working, for example with custom getters, but is there a way to do it simply with declared properties?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的解决方案就是
在
您的实现文件中。然后您可以通过 _items 访问可变集,但公共接口将是一个不可变集。
The easiest solution is
and then just
inside your implementation file. Then you can access the mutable set through _items but the public interface will be an immutable set.
您必须将公共接口中的属性声明为只读,以便编译器不会抱怨。像这样:
Word.h
Word.m
You have to declare the property in the public interface as readonly in order the compiler not to complain. Like this:
Word.h
Word.m
您可以在实现中自己完成:
--- 实现文件 ---
You could just do it yourself in your implementation:
--- implementation file ---