Skip to content

Instantly share code, notes, and snippets.

@ddeville
Last active December 26, 2015 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddeville/7169443 to your computer and use it in GitHub Desktop.
Save ddeville/7169443 to your computer and use it in GitHub Desktop.
+keyPathsForValuesAffectingValueForKey: vs +keyPathsForValuesAffecting<Key>.
//
// main.m
// KVO
//
// Created by Damien DeVille on 10/26/13.
// Copyright (c) 2013 Damien DeVille. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Animal : NSObject
- (NSString *)identity;
@property (copy, nonatomic) NSString *name;
@end
@implementation Animal
- (NSString *)identity
{
return [NSString stringWithFormat:@"My name is %@.", [self name]];
}
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
{
NSMutableSet *keyPaths = [NSMutableSet setWithSet:[super keyPathsForValuesAffectingValueForKey:key]];
if ([key isEqualToString:@"identity"]) {
[keyPaths addObject:@"name"];
}
return keyPaths;
}
@end
#pragma mark -
@interface Monkey : Animal
@property (assign, nonatomic) NSUInteger age;
@end
@implementation Monkey
- (NSString *)identity
{
return [[super identity] stringByAppendingFormat:@" I am %lu.", [self age]];
}
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
{
NSMutableSet *keyPaths = [NSMutableSet setWithSet:[super keyPathsForValuesAffectingValueForKey:key]];
if ([key isEqualToString:@"identity"]) {
[keyPaths addObject:@"age"];
}
return keyPaths;
}
@end
#pragma mark -
@interface Animal (Funky)
@property (readonly, copy, nonatomic) NSString *funkyName;
@end
@implementation Animal (Funky)
- (NSString *)funkyName
{
NSString *name = [self name];
if (name == nil) {
return nil;
}
return [@"Funky " stringByAppendingString:name];
}
+ (NSSet *)keyPathsForValuesAffectingFunkyName
{
return [NSSet setWithObjects:@"name", nil];
}
@end
#pragma mark -
@interface Observer : NSObject
@end
@implementation Observer
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
// nop
}
@end
#pragma mark -
int main(int argc, const char **argv)
{
Monkey *monkey = [[Monkey alloc] init];
Observer *observer = [[Observer alloc] init];
[monkey addObserver:observer forKeyPath:@"identity" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:NULL];
[monkey addObserver:observer forKeyPath:@"funkyName" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:NULL];
[monkey setName:@"Bryan"];
[monkey setAge:12];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment