Skip to content

Instantly share code, notes, and snippets.

Created December 8, 2014 15:00
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
#import <Foundation/Foundation.h>
@interface FKItem : NSObject
@property(nonatomic) NSString * name;
@property(nonatomic) int price;
@implementation FKItem
@synthesize name;
@synthesize price;
@interface FKObserve: NSObject
@property (nonatomic, weak) FKItem * item;
-(void) showItemInfo;
@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);
int main (int argc, char * argv[])
@autoreleasepool {
FKItem * item = [[FKItem alloc] init];
[item setName:@"你好"];
[item setPrice:109];
FKObserve * ob = [[FKObserve alloc] init];
[ob setItem:item];
[ob showItemInfo];
[item setName:@"新你好"];
[item setPrice:119];
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