NSArray @property由NSMutableArray支持 [英] NSArray @property backed by a NSMutableArray
问题描述
我已经定义了一个类,我希望公共属性看起来像是由 NSArray
支持。这很简单,但在我的情况下,实际的支持ivar是 NSMutableArray
:
I've defined a class where I'd like a public property to appear as though it is backed by an NSArray
. That is simple enough, but in my case the actual backing ivar is an NSMutableArray
:
@interface Foo
{
NSMutableArray* array;
}
@property (nonatomic, retain) NSArray* array;
@end
在我的实施文件中( * .m
)我 @synthesize
该属性但我立即遇到警告,因为使用 self.words
与尝试修改 NSArray
相同。
In my implementation file (*.m
) I @synthesize
the property but I immediately run into warnings because using self.words
is the same as trying to modifying an NSArray
.
执行此操作的正确方法是什么?
What is the correct way to do this?
谢谢!
推荐答案
我会声明 readonly
NSArray
在您的标头中并覆盖该数组的getter以返回私有 NSMutableArray的副本
在您的实现中声明。请考虑以下事项。
I would declare a readonly
NSArray
in your header and override the getter for that array to return a copy of a private NSMutableArray
declared in your implementation. Consider the following.
Foo.h
@interface Foo
@property (nonatomic, retain, readonly) NSArray *array;
@end
Foo.m
@interface Foo ()
@property (nonatomic, retain) NSMutableArray *mutableArray
@end
#pragma mark -
@implementation Foo
@synthesize mutableArray;
- (NSArray *)array
{
return [[self.mutableArray copy] autorelease];
}
@end
这篇关于NSArray @property由NSMutableArray支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!