问题描述
我想声明一个公共不可变属性:
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
我想要的是实现中的可变集合,当从外部进行访问时,该集合将转换为不可变的集合. (我不在乎调用方是否可以将实例投射回NSMutableSet
并破坏封装.我住在一个安静,体面的小镇,这种情况不会发生.)
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.)
现在,我的编译器将实现内的属性视为NSSet
.我知道有很多方法可以使其工作,例如使用自定义getter,但是有没有一种方法可以简单地通过声明的属性来实现它?
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?
推荐答案
最简单的解决方案是
@interface Foo {
@private
NSMutableSet* _items;
}
@property (readonly) NSSet* items;
然后是
@synthesize items = _items;
位于您的实施文件中.然后,您可以通过_items访问可变集,但公共接口将是不可变的集.
inside your implementation file. Then you can access the mutable set through _items but the public interface will be an immutable set.
这篇关于如何声明由可变类型支持的不可变属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!