ios 利用kvc 监听可变数组变化
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 监听可变数组变化的更多相关文章
- 利用DOMNodeInserted监听标签内容变化
var exeFlag = 0;//控制执行业务次数标记$('#list1').bind('DOMNodeInserted', function () { if(!/img/.test($(" ...
- KVC和KVO实现监听容器类(数组等)的变化
KVC,即Key-Value Coding,键值编码,简单地说,就是可以由key获取一个object对应的property.举个例子,如果一个对象object,它有一个属性item,你可以通过valu ...
- iOS: 使用KVO监听控制器中数组的变化
一.介绍: KVO是一种能动态监听到属性值的改变的方式,使用场景非常广泛,这里我只讲如何监听控制器ViewController中数组的变化. 二.了解: 首先我们应该知道KVO是不能直接监听控制器Vi ...
- 详解vuex结合localstorage动态监听storage的变化
这篇文章主要介绍了详解vuex结合localstorage动态监听storage的变化,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看看吧 需求:不同组件间共用同一数据,当一个 ...
- Android监听手机网络变化
Android监听手机网络变化 手机网络状态发生变化会发送广播,利用广播接收者,监听手机网络变化 效果图 注册广播接收者 <?xml version="1.0" encodi ...
- 前端组件化Polymer入门教程(6)——监听属性值变化
监听属性值变化 如果需要监听属性值变化可以通过给observer赋值一个回调函数. <say-Hello></say-Hello> <dom-module id=&quo ...
- MutationObserver 监听DOM树变化
1 概述 Mutation observer 是用于代替 Mutation events 作为观察DOM树结构发生变化时,做出相应处理的API.为什么要使用mutation observer 去代替 ...
- HTML5 oninput实时监听输入框值变化的完美方案
在网页开发中经常会碰到需要动态监听输入框值变化的情况,如果使用 onkeydown.onkeypress.onkeyup 这个几个键盘事件来监测的话,监听不了右键的复制.剪贴和粘贴这些操作,处理组合快 ...
- 【转载】实时监听输入框值变化的完美方案:oninput & onpropertychange
oninput 是 HTML5 的标准事件,对于检测 textarea, input:text, input:password 和 input:search 这几个元素通过用户界面发生的内容变化非常有 ...
随机推荐
- webapi 跨域 (MVC-Web API: 405 method not allowed问题 )
使用webapi cors 1.安装包:Install-Package Microsoft.AspNet.WebApi.Cors –IncludePrerelease 2.在webapiconfig. ...
- 3、scala数组
一.Array .Array Buffer 1.Array 在Scala中,Array代表的含义与Java中类似,也是长度不可改变的数组. 此外,由于Scala与Java都是运行在JVM中,双方可以互 ...
- SpringBoot使用拦截器无效
附上代码: public class WendaWebConfiguration extends WebMvcConfigurerAdapter { @Autowired PassportInterc ...
- textarea的style="resize:none;"
<textarea class="form-control" id="gryj" rows="3" maxlength="3 ...
- 关于define
<?php define('local','localhost');//echo constant('local');exit(); define('username','root'); def ...
- hihoweek 137(简单完全背包)
题目链接:http://hihocoder.com/contest/hiho137/problem/1 题意:中文题诶- 思路:各层的成本计算不会有影响,所以我们只要把没一层的成本计算出来在求和就是答 ...
- iphone6 iphone6 plus 放大显示模式高分辨率模式问题
分为兼容模式和高分辨率模式. 兼容模式 当你的 app 没有提供 3x 的 LaunchImage 时,系统默认进入兼容模式,大屏幕一切按照 320 宽度渲染,屏幕宽度返回 320:然后等比例拉伸到大 ...
- Docker安装nginx以及负载均衡
首先在linux系统中新建一个data文件夹进行nginx容器的创建--即为:mkdir data. 一:第一次 1 第一步: 使用 docker pull nginx将nginx的镜像从仓库下载下来 ...
- maven scope 以及依赖传递
https://www.cnblogs.com/mxm2005/p/4947905.html
- Python内建函数一
内建函数 1. abs(number) 用法:返回数字的绝对值 2. all(iterable) 用法:如果iterable的所有元素都是真值,就返回True,否则返回False 3. any(ite ...