代码改变世界

iOS 开发笔记-Objective-C之KVC、KVO

  jiangys  阅读(423)  评论(0编辑  收藏  举报

概述

键值编码(KVC)、键值监听(KVO)特性

键值监听KVO

Key Value Observing(简称KVO)其实是一种观察者模式,利用它可以很容易实现视图组件和数据模型的分离,当数据模型的属性值改变之后作为监听器的视图组件就会被激发,激发时就会回调监听器自身。在ObjC中要实现KVO则必须实现NSKeyValueObServing协议,不过幸运的是NSObject已经实现了该协议,因此几乎所有的ObjC对象都可以使用KVO。

在ObjC中使用KVO操作常用的方法如下:

  • 注册指定Key路径的监听器: addObserver: forKeyPath: options:  context:
  • 删除指定Key路径的监听器: removeObserver: forKeyPathremoveObserver: forKeyPath: context:
  • 回调监听: observeValueForKeyPath: ofObject: change: context:

KVO的使用步骤也比较简单:

  1. 通过addObserver: forKeyPath: options: context:为被监听对象(它通常是数据模型)注册监听器 
  2. 重写监听器的observeValueForKeyPath: ofObject: change: context:方法
  3. 删除指定Key路径的监听器: removeObserver: forKeyPath、removeObserver: forKeyPath: context:

例子:

1.我们新建一个账号模型

Account.h

#import <Foundation/Foundation.h>

@interface Account : NSObject

/** 余额 */
@property (nonatomic, assign) float balance;

@end

2.在新建一个用户模型

Person.h

复制代码
#import <Foundation/Foundation.h>
@class Account;

@interface Person : NSObject

/** 名字 */
@property (nonatomic, copy) NSString *name;
/** 账号 */
@property (nonatomic, retain) Account *account;

@end
复制代码

3.在Person.m Model里使用

复制代码
//

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

@implementation Person

- (void)setAccount:(Account *)account
{
    _account = account;
    [self.account addObserver:self forKeyPath:@"balance" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"balance"]) {
        NSLog(@"keyPath=%@,object=%@,newValue=%.2f,context=%@",keyPath,object,[[change objectForKey:@"new"] floatValue],context);
    }
}

- (void)dealloc{
    [self.account removeObserver:self forKeyPath:@"balance"];// 移除监听
}

@end
复制代码

ViewController 就很简单了

复制代码
- (void)viewDidLoad {
    [super viewDidLoad];
    
    Person *person = [[Person alloc] init];
    person.name = @"jiangys";
    _account = [[Account alloc] init];
    person.account = _account;

    _account.balance = 2000; // 监听生效
}
复制代码

但是这种方式,是不能更新到界面的。可能使用到这种场景,比如 暂停,快进这些,不需要界面变化的好一些。如果需要界面变化,如账号余额的变化等,那就需要放在Controller里面去做UI的更新了。

复制代码
//
//  ViewController.m
//  KVO
//
//  Created by jiangys on 16/4/19.
//  Copyright © 2016年 Jiangys. All rights reserved.
//

#import "ViewController.h"
#import "Person.h"
#import "Account.h"

@interface ViewController ()
/** 账号 */
@property (nonatomic, retain) Account *account;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Person *person = [[Person alloc] init];
    person.name = @"jiangys";
    _account = [[Account alloc] init];
    person.account = _account;
    // 增加KVO监听
    [_account addObserver:self forKeyPath:@"balance" options:NSKeyValueObservingOptionNew context:nil];
    
    _account.balance = 2000;
    
    _account.balance = 1000;
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"balance"]) {
        NSLog(@"keyPath=%@,object=%@,newValue=%.2f,context=%@",keyPath,object,[[change objectForKey:@"new"] floatValue],context);
    }
}

- (void)dealloc{
    [_account removeObserver:self forKeyPath:@"balance"];// 移除监听
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
复制代码

 

KVO源代码下载:http://pan.baidu.com/s/1qYh7y8W

 

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示