我已经定义了一个类,我希望公共属性看起来好像是由一个NSArray.这很简单,但在我的情况下,实际的支持ivar是NSMutableArray:
@interface Foo
{
NSMutableArray* array;
}
@property (nonatomic, retain) NSArray* array;
@end
Run Code Online (Sandbox Code Playgroud)
在我的实现文件(*.m)我@synthesize的属性,但我立即遇到警告,因为使用self.words与尝试修改一样NSArray.
这样做的正确方法是什么?
谢谢!
我想声明一个公共不可变属性:
@interface Foo
@property(strong, readonly) NSSet *items;
@end
Run Code Online (Sandbox Code Playgroud)
...在实现文件中以可变类型支持:
@interface Foo (/* private interface*/)
@property(strong) NSMutableSet *items;
@end
@implementation
@synthesize items;
@end
Run Code Online (Sandbox Code Playgroud)
我想要的是实现中的可变集合,当从外部访问时,它会被转换为不可变的集合.(我并不关心调用者是否可以将实例强制转换NSMutableSet并打破封装.我住在一个安静,体面的城镇,这样的事情不会发生.)
现在我的编译器将属性视为NSSet实现内部.我知道有很多方法可以让它工作,例如使用自定义getter,但有没有办法简单地使用声明的属性?