Created
May 13, 2017 23:50
-
-
Save arkilis/b420249d3987d47d1ee27760a1ba9b92 to your computer and use it in GitHub Desktop.
kvo on viewcontroller
This file contains 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
// view controller.h | |
#import <UIKit/UIKit.h> | |
#import "Item.h" | |
@interface ViewController : UIViewController | |
@property (nonatomic, strong) NSString *myVal; | |
@end | |
// view controller.m | |
#import "ViewController.h" | |
static void *context1 = &context1; | |
static void *context2 = &context2; | |
@implementation ViewController | |
- (void)viewDidLoad { | |
[super viewDidLoad]; | |
// Do any additional setup after loading the view, typically from a nib. | |
[self setValue:@"some string" forKeyPath:@"myVal"]; | |
[self addObserver:self forKeyPath:@"myVal" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:context1]; | |
[self addObserver:self forKeyPath:@"myVal" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:context2]; | |
[self setValue:@"some string else" forKeyPath:@"myVal"]; | |
} | |
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ | |
if(context == context1){ | |
if ([keyPath isEqualToString:@"myVal"]) { | |
NSLog(@"The name of the child was changed."); | |
NSLog(@"%@", change); | |
} | |
} | |
if(context == context2){ | |
if ([keyPath isEqualToString:@"myVal"]) { | |
NSLog(@"The name of the child was changed."); | |
NSLog(@"%@", change); | |
} | |
} | |
} | |
- (void)didReceiveMemoryWarning { | |
[super didReceiveMemoryWarning]; | |
// Dispose of any resources that can be recreated. | |
} | |
@end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment