当前位置: 首页 > news >正文

KVO的使用

KVO的使用

 

KVO是一种设计模式,名为观察者.

addObserver:forKeyPath:options:context:

通知其他对象的方法,这个方法在NSObject中就已经申明了,也就是说任何继承自NSObject的对象都可以使用KVO.

我们来实现一个对象a值改变的时候去通知对象b.

新建两个ModelA ModelB 类.

ModelA.h + ModelA.m

#import <Foundation/Foundation.h>

@interface ModelA : NSObject

@property (nonatomic, strong) NSString *name;

@end
#import "ModelA.h"

@implementation ModelA

@end

ModelB.h + ModelB.m

#import <Foundation/Foundation.h>

@interface ModelB : NSObject

@property (nonatomic, strong) NSString *sex;

@end
#import "ModelB.h"

@implementation ModelB

-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary *)change
                      context:(void *)context
{
    self.sex = @"female";
}

@end

请将如下延时执行的代码添加进工程当中

- (void)delay:(int64_t)delta execute:(dispatch_block_t)block
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delta * NSEC_PER_SEC),
                   dispatch_get_main_queue(), block);
}

然后再写如下的代码:

执行结果如下:

2014-05-06 17:40:35.346 FileManager[20208:60b] Application windows are expected to have a root view controller at the end of application launch
2014-05-06 17:40:37.347 FileManager[20208:60b] female

如果注释掉ModelB中的方法observeValueForKeyPath:ofObject:change:context:,运行时会导致崩溃:

如果重复移除了两次,也会导致崩溃-_-!!!!

也就是这么一层关系:

A对象要通知B对象,B对象必须实现监听的方法,否则一旦有消息发送就会导致崩溃.

A对象不想通知B对象了,需要从B对象身上移除掉通知.

 

要想程序不出现问题,我们需要实现3步.

(主动添加B的通知) A -------> B(不实现一个方法就崩溃)

(主动移除B的通知) A ---X-->  B

(重复移除B的通知) A ---X-->  B(崩溃)

用起来很恶性,还好,我们可以重复添加B的通知而不崩溃......

 

 

问题:在ARC中我们需要移除KVO的observer么?

You should explicitly remove the observer even you use ARC. Create a dealloc method and remove there..

-(void)dealloc {[[NSNotificationCenter defaultCenter] removeObserver:self];}

If you see the method you don't need to call [super dealloc]; here, only the method without super dealloc needed.

你需要非常明确的移除你的通知者,即使是在ARC中.创建一个dealloc方法然后在方法里面移除.

ARC中你不需要调用[super dealloc].

 

 

问题:ARC给一个对象添加了observer有可能会导致循环应用什么的么?

You need to call removeObserver, ARC only automates retain counts. removeObserver does not impact the retain count.

你需要调用removeObserver,ARC只是自动管理了retain counts,removeObserver并不影响retain count.(这一点我不确定,有待验证)

 

 

问题:当要通知的对象已经nil了,这个通知会自动移除吗?

Observers are not removed automatically. From the NSNotificationCenter Class Reference:

观察者不会自动移除,请查看NSNotificationCenter类的原文引述:

Important: The notification center does not retain its observers, therefore, you must ensure that you unregister observers (using removeObserver: or removeObserver:name:object:) before they are deallocated. (If you don't, you will generate a runtime error if the center sends a message to a freed object.)

很重要:通知中心并不会retain他的观察者,所以,你必须确保你那些对象销毁之前注销掉观察者,否则就会出现错误.

You should therefore call

[[NSNotificationCenter defaultCenter] removeObserver:self];

in your dealloc method if you are not 100% sure that the observer was not removed previously.

 

 

 

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSKeyValueObserving_Protocol/Reference/Reference.html#//apple_ref/occ/instm/NSObject/addObserver%3aforKeyPath%3aoptions%3acontext%3a

addObserver:forKeyPath:options:context:

Registers anObserver to receive KVO notifications for the specified key-path relative to the receiver.

- (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
Parameters
anObserver

The object to register for KVO notifications. The observer must implement the key-value observing method observeValueForKeyPath:ofObject:change:context:.

keyPath

The key path, relative to the receiver, of the property to observe. This value must not be nil.

options

A combination of the NSKeyValueObservingOptions values that specifies what is included in observation notifications. For possible values, see “NSKeyValueObservingOptions.”

context

Arbitrary data that is passed to anObserver in observeValueForKeyPath:ofObject:change:context:.

Discussion

Neither the receiver, nor anObserver, are retained.

 

转载于:https://www.cnblogs.com/YouXianMing/p/3712160.html

相关文章:

  • 自动化测试
  • Unicode编码字符 转换成汉字
  • 简单用户管理系统(P-05)
  • typedef 与指针、多维数组
  • 32、mysql数据库增删改查
  • Android -- 保存文件
  • ORACLE EXECUTE IMMEDIATE 用法详解
  • SpringMVC使用@ResponseBody输出字符串时遇到的乱码问题及解决办法
  • 【Advanced Windows Phone Programming】在windows phone 8中解码mp3 和编码pcm
  • JavaScript创建对象(五)——动态原型模式
  • Asp.Net Mvc + ComBoost.Mvc快速开发
  • Laravel Mix运行时关于es2015报错解决方案
  • 建站初级指南
  • 一个ViewGroup#dispatchDraw()中的NP分析
  • LINUX命令 cp: omitting directory 出现的问题解决办法
  • [数据结构]链表的实现在PHP中
  • 《剑指offer》分解让复杂问题更简单
  • 【JavaScript】通过闭包创建具有私有属性的实例对象
  • 【跃迁之路】【444天】程序员高效学习方法论探索系列(实验阶段201-2018.04.25)...
  • 07.Android之多媒体问题
  • bearychat的java client
  • CAP 一致性协议及应用解析
  • JS学习笔记——闭包
  • ng6--错误信息小结(持续更新)
  • react-core-image-upload 一款轻量级图片上传裁剪插件
  • React中的“虫洞”——Context
  • Traffic-Sign Detection and Classification in the Wild 论文笔记
  • vue从创建到完整的饿了么(18)购物车详细信息的展示与删除
  • 阿里中间件开源组件:Sentinel 0.2.0正式发布
  • 基于 Ueditor 的现代化编辑器 Neditor 1.5.4 发布
  • 计算机在识别图像时“看到”了什么?
  • 区块链分支循环
  • 如何邀请好友注册您的网站(模拟百度网盘)
  • 使用Gradle第一次构建Java程序
  • 数据结构java版之冒泡排序及优化
  • 整理一些计算机基础知识!
  • ​RecSys 2022 | 面向人岗匹配的双向选择偏好建模
  • ​ssh-keyscan命令--Linux命令应用大词典729个命令解读
  • ​七周四次课(5月9日)iptables filter表案例、iptables nat表应用
  • #LLM入门|Prompt#3.3_存储_Memory
  • #pragma 指令
  • #绘制圆心_R语言——绘制一个诚意满满的圆 祝你2021圆圆满满
  • (1)(1.9) MSP (version 4.2)
  • (16)UiBot:智能化软件机器人(以头歌抓取课程数据为例)
  • (Arcgis)Python编程批量将HDF5文件转换为TIFF格式并应用地理转换和投影信息
  • (附源码)spring boot儿童教育管理系统 毕业设计 281442
  • (附源码)计算机毕业设计SSM智能化管理的仓库管理
  • (求助)用傲游上csdn博客时标签栏和网址栏一直显示袁萌 的头像
  • (十六)串口UART
  • (四)模仿学习-完成后台管理页面查询
  • (学习日记)2024.01.09
  • (一)基于IDEA的JAVA基础1
  • (译) 理解 Elixir 中的宏 Macro, 第四部分:深入化
  • (转)负载均衡,回话保持,cookie
  • .NET Core引入性能分析引导优化