Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example program attached to Radar #
#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