KVO键值监听:

Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。

使用方式:

1. 注册,指定被观察者的属性,

2. 实现回调方法

3. 移除观察

上代码之前向大家说几个小坑,小白可以看,大神直接略过。

kvo直接监听NSMutableArray的时候,大家可能都认为count属于它的一个属性,当直接修改它的时候,count会发生变化,直接调用回调方法,事实上,kvo是无法直接监听count属性的,会直接崩溃,原因就不具体说了。怎么解决呢?我们可以新建一个model 来储存我们需要观察的NSMutableArray。好了,开始上代码;

新建 KVOModel.h

@interface KVOModel : NSObject

@property(nonatomic,strong)NSMutableArray *dataArray;

@end

ViewController中导入KVOModel.h

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)KVOModel *model;

- (void)viewDidLoad {

[super viewDidLoad];

self.view.backgroundColor=[UIColor whiteColor];

[self cteateUI];

[self loadDatasorce];

[self createBtn1];

[self createBtn2];

}

-(void)createBtn1{

UIButton *btn=[UIButton buttonWithType:UIButtonTypeSystem];

[btn setTitle:@"change1" forState:UIControlStateNormal];

btn.frame=CGRectMake(0, 0, 50, 44);

[self.view addSubview:btn];

[btn addTarget:self action:@selector(click1:) forControlEvents:UIControlEventTouchUpInside];

}

-(void)createBtn2{

UIButton *btn=[UIButton buttonWithType:UIButtonTypeSystem];

[btn setTitle:@"change2" forState:UIControlStateNormal];

btn.frame=CGRectMake(414-50, 0, 50, 44);

[self.view addSubview:btn];

[btn addTarget:self action:@selector(click2:) forControlEvents:UIControlEventTouchUpInside];

}

-(void)click1:(UIButton*)sender{

[[self.model mutableArrayValueForKey:@"dataArray"] addObject:[NSString stringWithFormat:@"%u",arc4random()%100-1]];

}

-(void)click2:(UIButton*)sender{

//数组进行删除的时候要使用kvc的方式

[[self.model mutableArrayValueForKey:@"dataArray"] removeLastObject];

}

-(void)cteateUI{

self.tableView=[[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];

self.tableView.delegate=self;

self.tableView.dataSource=self;

[self.view addSubview:self.tableView];

}

-(void)loadDatasorce{

self.model=[[KVOModel alloc]init];

[self.model addObserver:self forKeyPath:@"dataArray" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];

self.model.dataArray=[NSMutableArray new];

for (NSInteger i=0;i<10; i++) {

//数组进行添加的时候要使用kvc的方式

[[self.model mutableArrayValueForKey:@"dataArray"] addObject:[NSString stringWithFormat:@"%ld",i]];

}

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

if ([keyPath isEqualToString:@"dataArray"]) {

// KVOModel * kvoModel=(KVOModel *)object;

// if (kvoModel.dataArray.count>=10) {

[_tableView reloadData];

// }

}

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

return 30;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

return  self.model.dataArray.count;

}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cellid"];

if (!cell) {

cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellid"];

}

cell.textLabel.text= self.model.dataArray[indexPath.row];

return cell;

}

//移除观察者

-(void)dealloc{

if (_model != nil) {

[_model removeObserver:self forKeyPath:@"dataArray"];

}

}

上机测试,ok,增加,删除都会触发tableview的刷新。

ios 利用kvc 监听可变数组变化的更多相关文章

  1. 利用DOMNodeInserted监听标签内容变化

    var exeFlag = 0;//控制执行业务次数标记$('#list1').bind('DOMNodeInserted', function () { if(!/img/.test($(" ...

  2. KVC和KVO实现监听容器类(数组等)的变化

    KVC,即Key-Value Coding,键值编码,简单地说,就是可以由key获取一个object对应的property.举个例子,如果一个对象object,它有一个属性item,你可以通过valu ...

  3. iOS: 使用KVO监听控制器中数组的变化

    一.介绍: KVO是一种能动态监听到属性值的改变的方式,使用场景非常广泛,这里我只讲如何监听控制器ViewController中数组的变化. 二.了解: 首先我们应该知道KVO是不能直接监听控制器Vi ...

  4. 详解vuex结合localstorage动态监听storage的变化

    这篇文章主要介绍了详解vuex结合localstorage动态监听storage的变化,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看看吧 需求:不同组件间共用同一数据,当一个 ...

  5. Android监听手机网络变化

    Android监听手机网络变化 手机网络状态发生变化会发送广播,利用广播接收者,监听手机网络变化 效果图 注册广播接收者 <?xml version="1.0" encodi ...

  6. 前端组件化Polymer入门教程(6)——监听属性值变化

    监听属性值变化 如果需要监听属性值变化可以通过给observer赋值一个回调函数. <say-Hello></say-Hello> <dom-module id=&quo ...

  7. MutationObserver 监听DOM树变化

    1 概述 Mutation observer 是用于代替 Mutation events 作为观察DOM树结构发生变化时,做出相应处理的API.为什么要使用mutation observer 去代替 ...

  8. HTML5 oninput实时监听输入框值变化的完美方案

    在网页开发中经常会碰到需要动态监听输入框值变化的情况,如果使用 onkeydown.onkeypress.onkeyup 这个几个键盘事件来监测的话,监听不了右键的复制.剪贴和粘贴这些操作,处理组合快 ...

  9. 【转载】实时监听输入框值变化的完美方案:oninput & onpropertychange

    oninput 是 HTML5 的标准事件,对于检测 textarea, input:text, input:password 和 input:search 这几个元素通过用户界面发生的内容变化非常有 ...

随机推荐

  1. @SpringBootApplication注解分析

    首先我们分析的就是入口类Application的启动注解@SpringBootApplication,进入源码: @Target(ElementType.TYPE) @Retention(Retent ...

  2. Code:获取指定汉字的首字母

    ylbtech-Code:获取指定汉字的首字母 1.获取指定汉字的首字母返回顶部 1. /// <summary> /// 获取指定汉字的首字母 /// </summary> ...

  3. The Tomcat server configuration at \Servers\Tomcat v8.0 Server at localhost-config is missing. Check the server for erro

    解决方案 1.选择Eclipse工具栏中的Windows→Perferences 2.remove已经创建的server 3.选择Add重新添加,选择create anew local server ...

  4. sqlServer对内存的管理

    简介 理解SQL Server对于内存的管理是对于SQL Server问题处理和性能调优的基本,本篇文章讲述SQL Server对于内存管理的内存原理. 二级存储(secondary storage) ...

  5. CodeForces 1118F2. Tree Cutting (Hard Version)

    题目简述:给定$n \leq 3 \times 10^5$个节点的树,其中一部分节点被染色,一共有$k$种不同的颜色.求将树划分成 $k$ 个不相交的部分的方案数,使得每个部分中除了未染色的节点以外的 ...

  6. lua调用c函数

    参考:http://blog.163.com/madahah@126/blog/static/170499225201121504936823/ 1.编辑C程序 vim luac.c #include ...

  7. 设置Mvc路由Asp.net 与 mvc同用

    App_start/RouteConfig.cs/RegisterRoutes(RouteConllection routes) { routes.IgnoreRoute("{resourc ...

  8. UNPIVOT逆透视以及动态逆透视存储过程

    前几天一直练习PIVOT透视,还实现了动态透视的存过程<动态透视表>https://www.cnblogs.com/insus/p/10888277.html 今天练习MS SQL Ser ...

  9. SpringCloud学习系列之七 ----- Zuul路由网关的过滤器和异常处理

    前言 在上篇中介绍了SpringCloud Zuul路由网关的基本使用版本,本篇则介绍基于SpringCloud(基于SpringBoot2.x,.SpringCloud Finchley版)中的路由 ...

  10. [Xcode 实际操作]七、文件与数据-(7 )使用UserDefaults检测App是否首次运行

    目录:[Swift]Xcode实际操作 本文将演示UserDefaults的使用,它常被用于存储程序的配置数据. 当关闭程序之后,再次打开程序时,之前存储的数据依然可以从UserDefaults里读取 ...