以下是我自己写的代码,方便新手理解kvo模式的流程。
思路,创建Person类,年龄属性,
show类负责显示Person对象,年龄显示的变化。
用kvo模式。
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Show.h"
int main(int argc, const char * argv[]) {
Person *p = [[Person alloc]init];
p.age=11;
Show *s = [[Show alloc]initWithPerson:p];
[p setValue:@22 forKey:@"age"];
[p setValue:@23 forKey:@"age"];
// NSLog(@"%ld",p.age);
return 0;
}
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)NSInteger age;
@end
#import "Person.h"
@implementation Person
@end
#import <Foundation/Foundation.h>
#import "Person.h"
@interface Show : NSObject
@property(nonatomic,retain)Person *person;
- (id)initWithPerson:(Person *)per;
@end
------------------------#import "Show.h"
@implementation Show
- (id)initWithPerson:(Person *)per{
self = [super init];
if(self){
_person = per;
/*注意这里:把创建的per对象,即p,赋值给show里面的Person类属性,即设置,要拿出来还要生成get方法,所以这里不能简单的写个属性,直接@property()即可。*/
//_person = [per retain];
[_person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"age"]){
NSNumber *age = [change objectForKey:@"new"];
NSInteger newage = [age integerValue];
NSLog(@"现在的age是%ld",newage);
}else{
NSLog(@"error");
}
}
- (void)dealloc{
[_person removeObserver:self forKeyPath:@"age"];
}
@end