Skip to content

Instantly share code, notes, and snippets.

@vastus
Created February 18, 2015 21:09
Show Gist options
  • Select an option

  • Save vastus/32cd102be84712bc5176 to your computer and use it in GitHub Desktop.

Select an option

Save vastus/32cd102be84712bc5176 to your computer and use it in GitHub Desktop.
Feed dog when it's hungry (w/ the help of observers) #objc
//
// Dog.h
// Fiddle
//
// Created by Juho H on 18/02/15.
// Copyright (c) 2015 Juho Hautala. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Dog : NSObject
@property int hunger;
- (void)liveAnHour;
@end
//
// Dog.m
// Fiddle
//
// Created by Juho H on 18/02/15.
// Copyright (c) 2015 Juho Hautala. All rights reserved.
//
#import "Dog.h"
@interface Dog ()
//@property int hunger;
@end
@implementation Dog
- (instancetype)init {
if (self = [super init]) {
_hunger = 1;
}
return self;
}
- (void)liveAnHour {
// Have to access the magic setter.
// _hunger will not work here w/ observers.
self.hunger += 1;
}
@end
//
// main.m
// Fiddle
//
// Created by Juho H on 18/02/15.
// Copyright (c) 2015 Juho Hautala. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Dog.h"
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *me = [[Person alloc] init];
Dog *dog = [[Dog alloc] init];
[dog addObserver:me
forKeyPath:@"hunger"
options:NSKeyValueObservingOptionNew
context:nil];
NSLog(@"Dogs hunger: %@", [dog valueForKey:@"hunger"]);
[dog liveAnHour];
NSLog(@"Dogs hunger: %@", [dog valueForKey:@"hunger"]);
[dog liveAnHour];
NSLog(@"Dogs hunger: %@", [dog valueForKey:@"hunger"]);
[dog liveAnHour];
NSLog(@"Dogs hunger: %@", [dog valueForKey:@"hunger"]);
[dog removeObserver:me forKeyPath:@"hunger"];
}
return 0;
}
//
// Person.h
// Fiddle
//
// Created by Juho H on 18/02/15.
// Copyright (c) 2015 Juho Hautala. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject
@end
//
// Person.m
// Fiddle
//
// Created by Juho H on 18/02/15.
// Copyright (c) 2015 Juho Hautala. All rights reserved.
//
#import "Person.h"
#import "Dog.h"
@implementation Person
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqual: @"hunger"]) {
NSNumber *hunger = [object valueForKeyPath:keyPath];
if (3 < hunger.integerValue) {
[object setHunger:1];
NSLog(@"Dog fed");
}
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment