Skip to content

Instantly share code, notes, and snippets.

@Tricertops
Last active August 29, 2015 14:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tricertops/a1f8fd3105bd5986e1ad to your computer and use it in GitHub Desktop.
Save Tricertops/a1f8fd3105bd5986e1ad to your computer and use it in GitHub Desktop.
Maybe the simplest way to implement Key-Value Observing compliant collection.
// This triggers correct KVO insertion notification:
[parent.mutableChildren addObject:@"Child"];
// Key "children" is fully KVO compliant:
@property (atomic, readwrite, copy) NSArray *children;
@property (atomic, readonly, strong) NSMutableArray *mutableChildren;
@property (atomic, readonly, strong) NSMutableArray *internalChildren;
- (instancetype)init {
self = [super init];
if (self) {
self->_internalChildren = [[NSMutableArray alloc] init];
}
return self;
}
- (NSArray *)children {
return [self->_internalChildren copy];
}
- (void)setChildren:(NSArray *)children {
[self ->_internalChildren setArray:children];
}
// Forwards collection changes from internal to public `children`.
+ (NSSet *)keyPathsForValuesAffectingChildren {
return [NSSet setWithObject:@"internalChildren"];
}
// Mutable proxy works with internal collection that has NO setter. This is important!
- (NSMutableArray *)mutableChildren {
return [self mutableArrayValueForKey:@"internalChildren"];
}
@Tricertops
Copy link
Author

In case you don't need -setChildren: you could do this without the internal property by synthesizing _mutableChildren and using key “children” in -mutableArrayValueForKey:.

How this works is described in Accessor Search Pattern for Ordered Collections.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment