Skip to content

Instantly share code, notes, and snippets.

@period331
Created December 8, 2014 15:00
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 period331/650cca19ea383c8c614a to your computer and use it in GitHub Desktop.
Save period331/650cca19ea383c8c614a to your computer and use it in GitHub Desktop.
observe.m
#import <Foundation/Foundation.h>
@interface FKItem : NSObject
@property(nonatomic) NSString * name;
@property(nonatomic) int price;
@end
@implementation FKItem
@synthesize name;
@synthesize price;
@end
@interface FKObserve: NSObject
@property (nonatomic, weak) FKItem * item;
-(void) showItemInfo;
@end
@implementation FKObserve
@synthesize item = _item;
- (void) showItemInfo
{
NSLog(@"物品名称: %@, 价格为: %d", [_item name], [_item price]);
}
- (void) setItem:(FKItem *)item
{
// self.item = item;
[self.item addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
[self.init addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew context:nil];
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"----observe 方法被调用");
NSLog(@"被修改的keyPath为: %@", keyPath);
NSLog(@"被修改的对象为: %@", object);
NSLog(@"被修改的属性值为: %@", change);
NSLog(@"context: %@", context);
}
@end
int main (int argc, char * argv[])
{
@autoreleasepool {
FKItem * item = [[FKItem alloc] init];
[item setName:@"你好"];
[item setPrice:109];
NSLog(@"%@", item.name);
FKObserve * ob = [[FKObserve alloc] init];
[ob setItem:item];
[ob showItemInfo];
[item setName:@"新你好"];
[item setPrice:119];
NSLog(@"东西呢?");
}
}
clang -fobjc-arc -framework Foundation FKOberve.m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment