I just noticed that calling addObject: on an NSMutableArray doesn’t access that array’s setter.
E.g., for NSMutableArray self.myArray, [self.myArray addObject:object] does not use [self setMyArray:array] to add the object.
Previously I have been using custom setters and getter to check assignment before assigning; e.g., if I wanted an array that only accepted objects of class MyClass, I would do the following:
- (void)setMyArray:(NSMutableArray *)myArray
{
for (id object in myArray)
{
if (![object isKindOfClass:[MyClass class]]) return;
}
_myArray = myArray;
}
- (NSMutableArray *)myArray
{
if (!_myArray) _myArray = [[NSMutableArray alloc] init];
_myArray = myArray;
}
How do I go about achieving this same functionality when changing the array via addObject:, removeObject:, and other similar functions that may circumvent the setter?
Generally this kind of problem is the reason why
NSMutableArrayis usually avoided in preference ofNSArray.This is the simple solution, use NSArray instead of NSMutableArray:
However, if the array is really big that will cause performance issues. Then you’ve got two options:
addObjectToMyArray:method in your class and always use thatNSArrayControllerand use that to access your array. It will implement key value observing and bindings and all of that stuff.NSMutableArrayis designed to performaddObject:with as few CPU instructions as possible and therefore does not proved any way for external code to be notified that the object was added. You have to have some other class wrapped around it.Do not try to subclass
NSMutableArray, because it is a “class cluster” making subclasses extremely complicated.