Created
November 5, 2015 22:12
-
-
Save armadsen/74d68f8689a8af471fa4 to your computer and use it in GitHub Desktop.
Example program attached to Radar #
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
#import <Foundation/Foundation.h> | |
@interface Foo : NSObject | |
@property (nonatomic, strong) NSArray *bars; | |
- (void)addBar:(NSString *)bar; | |
- (void)removeBar:(NSString *)bar; | |
@end | |
@interface Foo () | |
@property (nonatomic, strong) NSMutableArray *internalBars; | |
@end | |
@implementation Foo | |
- (instancetype)init | |
{ | |
self = [super init]; | |
if (self) { | |
_internalBars = [NSMutableArray array]; | |
} | |
return self; | |
} | |
+ (NSSet *)keyPathsForValuesAffectingBars { return [NSSet setWithObjects:@"internalBars", nil]; } | |
- (NSArray *)bars { return [self.internalBars copy]; } | |
- (void)setBars:(NSArray *)names { self.internalBars = [names ?: @[] mutableCopy]; } | |
- (void)addBar:(NSString *)bar | |
{ | |
[self insertObject:bar inInternalBarsAtIndex:self.internalBars.count]; | |
} | |
- (void)removeBar:(NSString *)bar | |
{ | |
NSUInteger index = [self.internalBars indexOfObject:bar]; | |
if (index == NSNotFound) return; | |
[self removeObjectFromInternalBarsAtIndex:index]; | |
} | |
- (void)insertObject:(NSString *)object inInternalBarsAtIndex:(NSUInteger)index | |
{ | |
[self.internalBars insertObject:object atIndex:index]; | |
} | |
- (void)removeObjectFromInternalBarsAtIndex:(NSUInteger)index | |
{ | |
[self.internalBars removeObjectAtIndex:index]; | |
} | |
@end | |
@interface Observer : NSObject | |
@end | |
@implementation Observer | |
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context | |
{ | |
NSLog(@"Change kind: %@", change[NSKeyValueChangeKindKey]); | |
} | |
@end | |
int main(int argc, char *argv[]) { | |
@autoreleasepool { | |
NSString *keyPathToObserve = @"bars"; // Change kind will always be NSKeyValueChangeSetting (1) | |
//NSString *keyPathToObserve = @"internalBars"; // Change kind will be correct | |
Observer *observer = [[Observer alloc] init]; | |
Foo *foo = [[Foo alloc] init]; | |
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld; | |
[foo addObserver:observer forKeyPath:keyPathToObserve options:options context:NULL]; | |
[foo addBar:@"Hello"]; | |
[foo addBar:@"KVO"]; | |
[foo addBar:@"Is"]; | |
[foo removeBar:@"KVO"]; | |
[foo addBar:@"Great"]; | |
[foo removeObserver:observer forKeyPath:keyPathToObserve]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment