ios 监听数组个数的变化_【iOS】KVO方式监听数组的变化动态刷新tableView
写作本文来由: iOS默认不支持对数组的KVO,因为普通方式监听的对象的地址的变化,而数组地址不变,而是里面的值发生了改变
整个过程需要三个步骤 (与普通监听一致)
/*
*第一步建立观察者及观察的对象
* 第二步 处理key的变化(根据key的变化刷新UI)
* 第三步 移除观察者
*/
数组不能放在UIViewController里面,在这里面的数组是监听不到数组大小的变化的,需要将需要监听的数组封装到model里面<
model类为: 将监听的数组封装到model里,不能监听UIViewController里面的数组
两个属性 一个 字符串类的姓名,一个数组类的modelArray,我们需要的就是监听modelArray里面元素的变化
@interface model : NSObject
@property(nonatomic, copy)NSString *name;
@property(nonatomic, retain)NSMutableArray *modelArray;
1 建立观察者及观察的对象
第一步 建立观察者及观察的对象
[_modeladdObserver:selfforKeyPath:@"modelArray"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:NULL];
第二步 处理key的变化(根据key的变化刷新UI)
最重要的就是添加数据这里
不能这样 [_model.modelArray addObject]方法,需要这样调用 [[_model mutableArrayValueForKey:@"modelArray"] addObject:str];原因稍后说明。
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"modelArray"]) {
[_tableView reloadData];
}
}
第三步 移除观察者
if (_model != nil) {
[_model removeObserver:self forKeyPath:@"modelArray"];
}
以下附上本文代码:
代码中涉及三点
1 根据数组动态刷新tableview;
2 定时器的使用(涉及循环引用问题);
3 使用KVC优化model的初始化代码。
没找到上传整个工程的方法,暂时附上代码
1 NSTimer相关
//
// NSTimer+DelegateSelf.h
// KVOTableview
//
// Created by 程立彬 on 14-8-8.
// Copyright (c) 2014年 chenglb. All rights reserved.
//
//为防止controller和nstimer之间的循环引用,delegate指向当前单例,而不指向controller
#import
@interface NSTimer (DelegateSelf)
+(NSTimer *)scheduledTimerWithTimeInterval:(int)timeInterval block:(void(^)())block repeats:(BOOL)yesOrNo;
@end
//
// NSTimer+DelegateSelf.m
// KVOTableview
//
// Created by 程立彬 on 14-8-8.
// Copyright (c) 2014年 chenglb. All rights reserved.
//
#import "NSTimer+DelegateSelf.h"
@implementation NSTimer (DelegateSelf)
+(NSTimer *)scheduledTimerWithTimeInterval:(int)timeInterval block:(void(^)())block repeats:(BOOL)yesOrNo
{
return [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(callBlock:) userInfo:[block copy] repeats:yesOrNo];
}
+(void)callBlock:(NSTimer *)timer
{
void(^block)() = timer.userInfo;
if (block != nil) {
block();
}
}
@end
2 model相关
//
// model.h
// KVOTableview
//
// Created by 程立彬 on 14-8-8.
// Copyright (c) 2014年 chenglb. All rights reserved.
//
#import
@interface model : NSObject
@property(nonatomic, copy)NSString *name;
@property(nonatomic, retain)NSMutableArray *modelArray;
-(id)initWithDic:(NSDictionary *)dic;
@end
//
// model.m
// KVOTableview
//
// Created by 程立彬 on 14-8-8.
// Copyright (c) 2014年 chenglb. All rights reserved.
//
//KVC的应用 简化冗余代码
#import "model.h"
@implementation model
-(id)initWithDic:(NSDictionary *)dic
{
self = [super init];
if (self) {
[self setValuesForKeysWithDictionary:dic];
}
return self;
}
-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
NSLog(@"undefine key ---%@",key);
}
@end
3 UIViewController相关
//
// RootViewController.m
// KVOTableview
//
// Created by 程立彬 on 14-8-8.
// Copyright (c) 2014年 chenglb. All rights reserved.
//
/*
* 第一步 建立观察者及观察的对象
* 第二步 处理key的变化(根据key的变化刷新UI)
* 第三步 移除观察者
*/
#import "RootViewController.h"
#import "NSTimer+DelegateSelf.h"
#import "model.h"
#define TimeInterval 3.0
@interface RootViewController ()
@property(nonatomic, retain)NSTimer *timer;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)model *model;
@end
@implementation RootViewController
- (void)dealloc
{
//第三步
if (_model != nil) {
[_model removeObserver:self forKeyPath:@"modelArray"];
}
//停止定时器
if (_timer != nil) {
[_timer invalidate];
_timer = nil;
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
NSDictionary *dic = [NSDictionary dictionaryWithObject:[NSMutableArray arrayWithCapacity:0] forKey:@"modelArray"];
self.model = [[model alloc] initWithDic:dic];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//第一步
[_model addObserver:self forKeyPath:@"modelArray" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
_tableView.delegate = self;
_tableView.dataSource = self;
_tableView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:_tableView];
//定时添加数据
[self startTimer];
}
//添加定时器
-(void)startTimer
{
__block RootViewController *bself = self;
_timer = [NSTimer scheduledTimerWithTimeInterval:TimeInterval block:^{
[bself changeArray];
} repeats:YES];
}
//增加数组中的元素 自动刷新tableview
-(void)changeArray
{
NSString *str = [NSString stringWithFormat:@"%d",arc4random()%100];
[[_model mutableArrayValueForKey:@"modelArray"] addObject:str];
}
//第二步 处理变化
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"modelArray"]) {
[_tableView reloadData];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_model.modelArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *cellidentifier = @"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifier];
}
cell.textLabel.text = _model.modelArray[indexPath.row];
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
ios 监听数组个数的变化_【iOS】KVO方式监听数组的变化动态刷新tableView相关推荐
- vue 监听map数组变化_解决vue无法侦听数组及对象属性的变化问题
一.数组 1.可以监听到的情况 如push.splice.=赋值(array=[1,2,3]) 2.无法监听到的情况 使用下标修改某个元素(这种比较常见) array[index] = 1 objec ...
- KVO方式监听数组的变化动态刷新tableView
写作本文来由: iOS默认不支持对数组的KVO,因为普通方式监听的对象的地址的变化,而数组地址不变,而是里面的值发生了改变 整个过程需要三个步骤 (与普通监听一致) /* * 第一步 建立观察者 ...
- java二维数组杨辉三角_实验----Java的二维数组的应用及杨辉三角的编写
(1) 编写一个程序,生成一个10*10的二维随机整数数组,并将该数组的每行最大值保存于一个一维数组中,将每列平均值保存于另外一个一维数组中并分别输出. (2) 编程输出杨辉三角的前10行. 找出一个 ...
- es6删除数组某一项_精学手撕系列——数组扁平化
参考文章:面试官连环追问:数组拍平(扁平化) flat 方法实现 编者荐语: 在前端面试中,手写flat是非常基础的面试题,通常出现在笔试或者第一轮面试中,主要考察面试者基本的手写代码能力和JavaS ...
- python定义数组是带指针_在cython中声明numpy数组和c指针
在我的代码中,我通常使用numpy数组在方法和类之间进行接口.为了优化程序的核心部分,我使用cython和那些numpy数组的c指针.不幸的是,我目前声明数组的方式相当长.在 例如,假设我有一个方法, ...
- 基类数组存放派生类_永远不要将派生类数组赋值给基类类型指针
C.152: Never assign a pointer to an array of derived class objects to a pointer to its base C.152:永远 ...
- java用数组存放账号密码_从零自学Java-7.使用数组存储信息
1.创建数组: 2.设置数组的大小: 3.为数组元素赋值: 4.修改数组中的信息: 5.创建多维数组: 6.数组排序. 程序SpaceRemover:显示输入字符串,并将其中所有的空格字符替换为句点字 ...
- java监控表变化_关于实时监控oracle数据库表数据变化的设计与实现
近期接受项目需求,需要实时处理oracle数据库中表的数据变化,首先想到的是在程序中创建定时器,轮询表.鉴于程序冗余考虑,百度知:oracle数据库java存储过程.Oracle数据库有执行简单jav ...
- python求数组的所有组合_使用numpy构建两个数组的所有组合的数组
这里是一个纯粹的numpy实现.它比使用迭代工具快约5×10.import numpy as npdef cartesian(arrays, out=None): """ ...
最新文章
- 节省 58% IT 成本,调用函数计算超过 30 亿次,石墨文档的 Serverless 实践
- 【Python】random模块生成多种类型随机数
- 太实用了,4款常用的可视化大屏工具,你一定要知道!
- java包含某个字符串_JavaScript判断一个字符串是否包含指定子字符串的方法
- 通过编写纯代码与JDBC实现对mysql的数据实现增删改查案例,jdbc连接数据库六步完整步骤详解,适合编程新手,通俗易懂
- 懂商业的技术合伙人(7):怎样快速开发一个APP(2)
- mst358 温控(热敏电阻)调试
- 2021年中国研究生数学建模竞赛B题——空气质量预报二次建模
- php微信jsapi支付案例,PHP实现微信支付(jsapi支付)流程
- 二进制颜色代码大全(含图)
- 程序猿生存指南-15 领导视察
- blast2go mysql_blast2go本地化-2017教程
- 火车售票-线程3种实现
- Kubernetes多节点二进制部署
- ideaIU_13.1.3安装图解。
- Windows通过注册表找出桌面壁纸文件存放路径
- Python 编写个情人节求爱对联
- Ubuntu16.04 python安装
- quartus-II软件中bdf和v文件的互相转换
- Terraform 学习总结(4)—— Terraform 实战
热门文章
- DPDK 锁:ticketlock和mcslock
- Linux进程管理+内存管理:进程切换的TLB处理(ASID-address space ID、PCID-process context ID)
- MessagePack简介及使用:一种有效的二进制序列化格式
- 监控和调整Linux网络协议栈的图解指南:接收数据
- Java实现二分查找算法
- springboot细节挖掘(集成ElasticSearch)
- mybatis ------ 懒加载(八)
- java输出 4 7什么意思_Java学习4_一些基础4_输入输出_16.5.7
- oracle生成顺序编号,Oracle排序以及序号的输出 | 学步园
- jquery ajax json传递数组,jQuery ajax 传递JSON数组到Spring Controller