KVO键值观察机制,就是MVC中Model变化的时候通知View更新,使用该机制避免了胶水代码,即在任何数据更新的地方都得写更新UI的更新代码。具体系统系统:NSObject,NSArray,NSSet三种KVO机制,API如下@interface NSObject(NSKeyValueObserverRegistration)
/* Register or deregister as an observer of the value at a key path relative to the receiver. The options determine what is included in observer notifications and when they're sent, as described above, and the context is passed in observer notifications as
described above.
*/
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
@end
@interface NSArray(NSKeyValueObserverRegistration)
/* Register or deregister as an observer of the values at a key path relative to each indexed element of the array. The options determine what is included in observer notifications and when they're sent, as described above, and the context is passed in observer
notifications as described above. This is not merely a convenience method; invoking this this is potentially much faster than repeatedly invoking -[NSObject(NSKeyValueObserverRegistration) addObserver:forKeyPath:options:context:].
*/
- (void)addObserver:(NSObject *)observer toObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
- (void)removeObserver:(NSObject *)observer fromObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath;
/* NSArrays are not observable, so these methods raise exceptions when invoked on NSArrays. Instead of observing an array, observe the ordered to-many relationship for which the array is the collection of related objects.
*/
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
@end
@interface NSSet(NSKeyValueObserverRegistration)
/* NSSets are not observable, so these methods raise exceptions when invoked on NSSets. Instead of observing a set, observe the unordered to-many relationship for which the set is the collection of related objects.
*/
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context NS_AVAILABLE(10_4, 2_0);
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath NS_AVAILABLE(10_4, 2_0);
@end
只解释@interfaceNSObject(NSKeyValueObserverRegistration)
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
例如:
Class Model:NSObject
{
NSString *text;
}
Class Controller:NSObject
{
Model *model;
}
此时如果在Controller中想使用KVO机制得如下操作
[model addObserver:self forKeyPath:@“text” options:NSKeyValueObservingOptionNew context:nil];
这条语句意思是:当model的text属性变化时通知self,其中NSKeyValueObservingOptionNew 可以变换,context参数是void*类型,因此可以传递自己想传递的任何类型。
除此在Controller中还得实现
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
text属性变化时系统会回调这个函数,因此在这个函数中更新UI。
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
删除观察者记得在释放本对象之前一定要remove observer,比如在dealloc中remove observer。
- (void)addObserver:(NSObject *)observer toObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
向数组中某个对象集合添加观察者
相关推荐
python后端的支付宝小程序用户认证问题(alipay-sdk-python、pycrypto无法安装)
python后端的支付宝小程序用户认证问题(alipay-sdk-python、pycrypto无法安装) 写在前面 事先说明,本人不是大佬,我只是在不断探索的途中找到了解决这个问题的方法,之前在网上搜索的时候没有看到相关文章,所以就来简单讲一下。 正文 借着蚂蚁金服小程序大赛开通了支付宝小程序个人开发者,尝试将一个微信小程序的项目移植到支付宝上,支付宝对于用户唯一id的获取比微信要复杂很多,微信...
[深入浅出Cocoa]详解键值观察(KVO)及其实现机理
[深入浅出Cocoa]详解键值观察(KVO)及其实现机理 罗朝辉 (http://blog.youkuaiyun.com/kesalin/) 本文遵循“署名-非商业用途-保持一致”创作公用协议 一,前言 Objective-C 中的键(key)-值(value)观察(KVO)并不是什么新鲜事物,它来源于设计模式中的观察者模式,其基本思想就是: 一个目标对象管理所有依赖于它的观察者
医疗AI新思路:为什么Graph Neural Network能改善气道分割的漏检问题?
本文探讨了Graph Neural Network(GNN)在医疗AI领域改善气道分割漏检问题的创新应用。通过分析3D UNet等传统方法的局限性,揭示了GNN在图结构建模中的独特优势,特别是在捕捉细小末梢支气管方面的突破性表现。文章详细介绍了UNet-GNN混合架构的设计原理、实验性能对比及优化方向,为CT影像分析提供了新思路。
Objective-C 的 KVO(二):NSKeyValueObserving.h 代码注释
/* NSKeyValueObserving.h Copyright (c) 2003-2019, Apple Inc. All rights reserved. */ #import <Foundation/NSArray.h> #import <Foundation/NSOrderedSet.h> #import <Foundation/NSSet.h> #import <Foundation/NSDictionary.h> @class NSInde
【WILEY】从Revision到Online:逐层拆解投稿状态更新与关键文件提交实战
本文详细解析了学术论文从返修到在线发表的全过程,重点拆解了投稿系统状态更新背后的含义与应对策略。文章提供了返修稿与回复信的准备技巧、关键补充文件(如图文摘要)的提交要点,并分享了校对校样与处理出版协议的实战经验,帮助作者高效、专业地完成发表流程。
风机叶片小规模振动监测数据集--读取测试
ETH风电叶片缺陷数据集–读取测试 数据简介 提示:这里可以添加本文要记录的大概内容: 结构健康监测是保障重要机电设备、建筑设施健康的重要技术手段。 一、lvm_read包安装 示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务
iOS KVO
一、kvo概述kvo,全称Key-Value Observing,它提供了一种方法,当对象某个属性发生改变时,允许监听该属性值变化的对象可以接受到通知,然后通过kvo的方法响应一些操作。二、kvo实现原理kvo是如何实现通知对象的呢,其实这是通过Objective-C强大的runtime运行时机制实现的。当你第一次观察某个对象时,runtime会创建一个新的继承被监听类的子类。在这个新的类中,它会重
SAP HANA CDS View Syntax Options 全解:从语法到工程实践
本文面向SAP HANA工程师,深入解析CDS视图的语法与应用场景。文章涵盖XS Advanced环境下的CDS视图设计要点,包括SELECT基础语法、聚合函数与分组约束、参数化视图实现以及常见连接操作。特别强调工程实践中的注意事项:GROUP BY禁用表达式、原生表名大小写规范、结果集裁剪方式选择等。通过两个真实案例(办公室占用率统计和客户画像分析)展示CDS视图在实际业务中的应用,并提供性能优化建议。全文采用中英文混排规范,技术术语使用反引号标注,旨在为开发者提供清晰的CDS视图开发指南。
iOS开发-黑科技防止多次添加删除KVO出现的问题
一、使用场景 有时候我们会忘记添加多次KVO监听或者,不小心删除如果KVO监听,如果添加多次KVO监听这个时候我们就会接受到多次监听。 如果删除多次kvo程序就会造成catch,如下图 这时候我们就可以想一些方案来防止这种情况的发生。 二、使用技术 核心 : 利用runtime实现方法交换,进行拦截add和remove进行操作。 方案一 :利用 @try @ca
【蒸汽幻想台服新版商业端】2025最新整理单机一键即玩镜像端+WIN系半手工端+PC客户端+网页注册+网页管理后台+教程【站长亲测】
MMORPG端游【蒸汽幻想台服新版商业端】2025最新整理单机一键即玩镜像端+WIN系半手工端+PC客户端+网页注册+网页管理后台+教程。
【WRF数据介绍第二期】气象驱动场数据介绍及下载
【WRF数据介绍第二期】气象驱动场数据介绍及下载
主动呼叫KVO(NSKeyValueObserverNotification)
前言在做新项目的时候时候,产品的要求是某一页面在项目中以单例的形式存在的,`单例页面`的更新会受到`单例对象`的某个属性是不是发生变化而产生影响。如果`单例对象`中的某个属性在其他的页面中发生了变化,`单例页面`需要根据这个`单例对象`中的这个属性的值的变化而发生页面的更新。这个时候就需要`单例页面`用到KVO来进行监听`单例对象`中的属性。 最初的实现以下是单例对象中的某属性的set方法:- (v
OpenCV-Python图形图像处理:自用的一些工具函数源代码
本文为《OpenCV-Python图形图像处理:博主自用的一些工具函数功能及调用语法介绍》内容配套函数的源代码。
KVO (Key-Value-Observer, 键值观察)
KVO (Key-Value-Observer, 键值观察) valueForKey 和 valueForKeyPath区别 valueForKeyPath是valueForKey的升级, valueForKey都能用valueForKeyPath, valueForKey只能一层 KVC计算数组和 NSArray *array = @[@"1"...
深度学习工具包 DeepLearningToolbox
深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[](https://bitdeli.com/free "Bitdeli Badge")
文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况
主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。
KVO(键值观察)
添加键值观察者 @interface NSObject(NSKeyValueObserverRegistration) - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void
pscad IEEE标准系统搭建说明
pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。
iOS KVO详解
一、概述 KVO<NSKeyValueObserving>,是一个非正式协议,提供了一个途径,使对象(观察者)能够观察其他对象(被观察者)的属性,当被观察者的属性发生变化时,观察者就会被告知该变化。指定一个被观察对象(例如 A 类),当对象某个属性(例如 A 中的字符串 name)发生更改时,对象会获得通知,并作出相应处理;【且不需要给被观察的对象添加任何额外代码,就能使用 KVO ...
ET2012新版免狗免安装绿色软件
ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,
KVO的使用和本质
文章目录KVO的使用添加KVO后改变KVO本质手动调用KVO参考文献 KVO的使用 之前写过关于KVO原理的文章,最近在复习这里,再回去看感觉不是很清晰,就再写一篇吧 KVO的全称是Key-Value-Observing,人称键值监听,就是监听某个对象属性值的改变 KVO的使用很简单,其实就是给某个属性添加一个监听者,然后这个属性的值改变后,触发回调方法 self.student1 = [[ModelStudent alloc] init]; _student1.age = 10;
Objective-C学习篇第十二弹:键值观察KVO详解
设计模式
Objective-C:KVO机制
KVO:key value observer 键值对的观察者 功能:给对象属性添加观察者,用来时时监测对象属性值的改变,一旦属性值发生了改变,观察者就做出相应的反应,提醒用户。在应用中,针对MVC模式,数据库中的数据模型发生变化时,引起视图界面的改变,此时使用KVO进行数据的监测是一个不错的机制。 步骤: 1.添加观察者 2.接收变动通知 3.删除观察...
KVO 实战解析
前人已经说的很清楚了!我也没必要在重复了!我也没人家总结的好! 通过一个遛狗例子来解析KVO 下面介绍来自 http://www.cppblog.com/kesalin/archive/2012/11/17/kvo.html 总结的很全面 值得研究 一,前言 Objective-C 中的键(key)-值(value)观察(KVO)并不是什么新鲜事
iOS-KVO详解
(观察者模式:注册监听、事件回调) Key-Value-Observing ,一个对象能够观察另外一个对象的属性的值。当指定对象的属性被修改后,则对象就会接受到通知。(简单来说就是每次指定被观察的对象的属性被修改后,KVO就会自动通知响应的观察者了) 在OC中要实现KVO则必须实现NSKeyValueObserving协议,不过幸运的是NSObjkect已经实现了该协议。因...
KVO的使用
1、KVO 简介 KVO,是一个非正式协议,提供了一个途径,使对象(观察者)能够观察其他对象(被观察者)的属性, 当被观察者的属性发生变化时,观察者就会被告知该变化。 1.1 基本方法 添加观察者: - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueO...
【iOS】—— KVO传值
什么是KVO? KVO全称Key Value Observing,是苹果提供的一套事件通知机制。允许对象监听另一个对象特定属性的改变,并在改变时接收到事件。由于KVO的实现机制,只针对属性才会发生作用,一般继承自NSObject的对象都默认支持KVO。 KVO可以监听单个属性的变化,也可以监听集合对象的变化。通过KVC的mutableArrayValueForKey:等方法获得代理对象,当代理对象的内部对象发生改变时,会回调KVO监听的方法。集合对象包含NSArray和NSSet。 KVO的基本使用方法 K
KVC和KVO
KVC: KVO:- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context; 相当于观察者机制,当你观察的对象的值发生变化时会调用 - (void)observeValue
iOS开发之--路径(keyPath)、键值编码(KVC)和键值观察(KVO)
键路径 在一个给定的实体中,同一个属性的所有值具有相同的数据类型。 键-值编码技术用于进行这样的查找—它是一种间接访问对象属性的机制。 - 键路径是一个由用点作分隔符的键组成的字符串,用于指定一个连接在一起的对象性质序列。第一个键的性质是由先前的性质决定的,接下来每个键的值也是相对于其前面的性质。 键路径使您可以以独立于模型实现的方式指定相关对象的性质。通过...
KVO
添加观察方法: -(void)addObserver:(NSObject*)observerforKeyPath:(NSString*)keyPathoptions:(NSKeyValueObservingOptions)optionscontext:(void*)contex...
3642



被折叠的 条评论
为什么被折叠?



