码迷,mamicode.com
首页 > 移动开发 > 详细

iOS KVO和KVC简单使用

时间:2016-06-08 15:50:42      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

Account.h

#import <Foundation/Foundation.h>

@interface Account : NSObject

@property (nonatomic,assign) float balance;

@end

Account.m

#import "Account.h"

@implementation Account

@end

Person.h

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

@interface Person : NSObject
{
    @private int _age;
}

@property (nonatomic,copy) NSString * name;

@property (nonatomic,strong) Account * account;

- (void)showMessage;

@end

Person.m

#import "Person.h"

@implementation Person

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



@end

ViewController.m

#import "ViewController.h"
#import "Account.h"
#import "Person.h"
@interface ViewController ()
@property(nonatomic,strong)Person *person1;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _person1 = [[Person alloc] init];
    [_person1 setValue:@"zhaotian" forKey:@"name"];//KVC给person1.name赋值
    
    Account *account1 = [[Account alloc] init];
    [account1 setValue:@"100000.f" forKey:@"balance"];//KVC给account1.balance赋值
    
    [_person1 setValue:account1 forKey:@"account"];//KVC给person.account赋值
    //1.添加观察者改变 _person1.account.balance
    [_person1 addObserver:self forKeyPath:@"account.balance" options:NSKeyValueObservingOptionNew context:nil];
    
    
    _person1.account.balance = 20000000.f;
}
//2.监听的属性变化后获得的通知  _person1.account.balance改变后调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"account.balance"]) {
        NSLog(@"keyPath=%@,object=%@,newValue=%f,context=%@",keyPath,object,[[change objectForKey:@"new"] floatValue],context);
    }
}
//3.销毁观察者
- (void)dealloc{
    [_person1 removeObserver:self forKeyPath:@"account.balance"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

 

iOS KVO和KVC简单使用

标签:

原文地址:http://www.cnblogs.com/TianHero/p/5569922.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!