There are several ways to do this, but a sensible way is to maintain a private, mutable array, and then provide public read access. Then you just have an open accessory returning an immutable copy of the internal array. It will look something like this:
In the .h file:
@interface MyClass : NSObject @property (readonly) NSArray *publicArray; @end
In the .m file:
@interface MyClass () @property NSMutableArray *privateArray; @end @implementation MyClass + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key]; if ([key isEqualToString:@"publicArray"]) { keyPaths = [keyPaths setByAddingObject:@"privateArray"]; } return keyPaths; } @synthesize privateArray = _privateArray; - (NSArray *)publicArray { return [self.privateArray copy]; } @end
You can do without a copy if you are comfortable counting on a compiler to warn about code that tries to call mutation methods from the result of -publicArray , rather than excluding runtime exceptions. Another caveat is that without a copy, any changes to the private array will be βvisibleβ even in a previously received reference to a supposedly immutable array.
source share