Skip to content

Instantly share code, notes, and snippets.

@arkilis
Created May 13, 2017 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arkilis/b420249d3987d47d1ee27760a1ba9b92 to your computer and use it in GitHub Desktop.
Save arkilis/b420249d3987d47d1ee27760a1ba9b92 to your computer and use it in GitHub Desktop.
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