mapanguan

导航

KVC/KVO简单实例代码

Person.h
#import<Foundation/Foundation.h>

@classAccount;

@interfacePerson :NSObject{
@private
   int_age;
}
#pragma mark -属性

@property(nonatomic,copy)NSString*name;
@property(nonatomic,retain)Account*account;

-(void)showMessage;

@end

Person.m
#import"Person.h"
#import"Account.h"

@implementationPerson

-(void)showMessage{
   NSLog(@"name=%@,age=%d",_name,_age);
}

#pragma mark设置人员账户
-(void)setAccount:(Account*)account{
   _account=account;
   //添加对Account的监听
    [_accountaddObserver:selfforKeyPath:@"balance"options:NSKeyValueObservingOptionNewcontext:nil];
}

#pragma mark重写observeValueForKeyPath方法,当账户余额变化后此处获得通知
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context{
   if([keyPathisEqualToString:@"balance"]){//这里只处理balance属性
       NSLog(@"keyPath=%@,object=%@,newValue=%.2f,context=%@",keyPath,object,[[changeobjectForKey:@"new"]floatValue],context);
    }
}

#pragma mark重写销毁方法
-(void)dealloc{
    [self.accountremoveObserver:selfforKeyPath:@"balance"];//移除监听
}

Account.h
#import<Foundation/Foundation.h>

@interfaceAccount :NSObject
#pragma mark余额
@property(nonatomic,assign)floatbalance;
@end

Account.m
#import"Account.h"

@implementationAccount

@end

Main调用方法
- (void)viewDidLoad {
    [superviewDidLoad];

#if0
    Person *person1=[[Person alloc]init];
    [person1 setValue:@"Kenshin"forKey:@"name"];
    [person1 setValue:@28forKey:@"age"];//注意即使一个私有变量仍然可以访问

    [person1 showMessage];
   //结果:name=Kenshin,age=28
    NSLog(@"person1's name is :%@,age is :%@",person1.name,[person1 valueForKey:@"age"]);
   //结果:person1's name is :Kenshin,age is :28

    Account *account1=[[Account alloc]init];
    person1.account=account1;//注意这一步一定要先给account属性赋值,否则下面按路径赋值无法成功,因为account为nil,当然这一步骤也可以写成:[person1 setValue:account1 forKeyPath:@"account"];

    [person1 setValue:@100000000.0forKeyPath:@"account.balance"];

    NSLog(@"person1's balance is :%.2f",[[person1 valueForKeyPath:@"account.balance"] floatValue]);
   //结果:person1's balance is :100000000.00

#else

   Person*person1=[[Personalloc]init];
    person1.name=@"Kenshin";

   Account*account1=[[Accountalloc]init];
    account1.balance=100000000.0;
    person1.account=account1;

    account1.balance=200000000.0;//注意执行到这一步会触发监听器回调函数observeValueForKeyPath: ofObject: change: context:
#endif

}

 

posted on 2016-05-10 13:49  mapanguan  阅读(164)  评论(0编辑  收藏  举报