observe.m
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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