Skip to content

Instantly share code, notes, and snippets.

@arkilis arkilis/kvo.m
Created May 13, 2017

Embed
What would you like to do?
kvo on viewcontroller
// 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
You can’t perform that action at this time.