I'd like to implement KVO for an NSArray
property that is declared as readonly
. The getter for this readonly
property returns a copy of the private NSMutableArray
that backs the backs the public readonly
one:
In my .h
:
@interface MyClass : NSObject
@property (readonly, nonatomic) NSArray *myArray;
- (void)addObjectToMyArray:(NSObject *)obj;
- (void)removeObjectFromMyArray:(NSObject *)obj;
@end
And in my .m
:
@interface MyClass()
@property (strong, nonatomic) NSMutableArray *myPrivateArray;
@end
@implementation MyClass
- (NSArray *)myArray {
return (NSArray *)[self.myPrivateArray copy];
}
- (void) addObjectToMyArray:(NSObject *)obj {
[self willChangeValueForKey:@"myArray"];
[self.myPrivateArray addObject:obj];
[self didChangeValueForKey:@"myArray"];
}
- (void) removeObjectToMyArray:(NSObject *)obj {
[self willChangeValueForKey:@"myArray"];
[self.myPrivateArray removeObject:obj];
[self didChangeValueForKey:@"myArray"];
}
@end
In my tests, I am seeing an exception thrown when I call didChangeValueForKey:
. Is this the correct way to do this?