Read-only NSMutableArray and NSCoding?

I have an NSMutableArray that should only be changed by the owner object (MyObject). therefore, the first attemp was to make this readonly property. The problem is that this class implements NSCoding, and NSCoding requires that archive objects be readwrite.

Then I thought about having private property (declared in the m file) and having a public method that returns my private array. But then it will be a reference to the array, and other classes will be able to modify it.

My methods should not return a copy of this array, because I want other classes to be able to modify each element = in this array, but not the array itself.

QUESTION:. How can I get a public property that is read-only, and at the same time be able to archive and unlock it?

+4
source share
1 answer

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.

+4
source

All Articles