iOS KVO和KVC简单使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS KVO和KVC简单使用相关的知识,希望对你有一定的参考价值。

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简单使用的主要内容,如果未能解决你的问题,请参考以下文章

原iOS中KVC和KVO的区别

iOS开发中KVCKVO简介

iOS开发中KVCKVO简介

IOS-KVC/KVO

iOS 代理与通知,kvc和kvo的区别

iOS KVC 和 KVO 的学习