Last active
August 29, 2015 14:01
-
-
Save Tricertops/a1f8fd3105bd5986e1ad to your computer and use it in GitHub Desktop.
Maybe the simplest way to implement Key-Value Observing compliant collection.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This triggers correct KVO insertion notification: | |
[parent.mutableChildren addObject:@"Child"]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Key "children" is fully KVO compliant: | |
@property (atomic, readwrite, copy) NSArray *children; | |
@property (atomic, readonly, strong) NSMutableArray *mutableChildren; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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"]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.