iOS KVO观察数组

import  "RootTableViewController.h"
#import
  "Stock.h"

@interface  RootTableViewController  ()
// 数组属性
@property  ( nonatomic ,  strong ) NSMutableArray  *dataSource;
@end

@implementation  RootTableViewController
- (
void )dealloc{
   
  // 移除观察者
    [
self  removeObserver : self  forKeyPath : @"dataSource" context : NULL ];
}
- (
void )viewDidLoad {
    [
super  viewDidLoad ];
   
  // 数组初始化
   
  self . dataSource  = [ NSMutableArray  array ];
   
  // 当前对象观察当前对象 dataSource 属性的变化
    [
self  addObserver : self  forKeyPath : @"dataSource" options : NSKeyValueObservingOptionOld  context : NULL ];
   
  //
   
  UIBarButtonItem  *right = [[ UIBarButtonItem  alloc ] initWithBarButtonSystemItem : UIBarButtonSystemItemAdd  target : self action : @selector (addSomething:)];
   
  self . navigationItem . rightBarButtonItem  = right;
   
  // 注册 cell
    [
self . tableView  registerClass :[ UITableViewCell  class ] forCellReuseIdentifier : @"cell" ];
   
}
- (
void )addSomething:( UIBarButtonItem  *)sender{
   
  Stock  *stock = [[ Stock  alloc ]  init ];
    stock.
stockName  =  @" 中石化 " ;
   
  int  a =  arc4random () %  1000  +  1 ;
    stock.
price  = a /  1.1 ;
    [
self  insertObject :stock inDataSourceAtIndex : self . dataSource . count ];
   
}

- (
void )observeValueForKeyPath:( NSString  *)keyPath ofObject:( id )object change:( NSDictionary  *)change context:( void *)context{
   
  if  ([change[ @"kind" ]  integerValue ] ==  NSKeyValueChangeInsertion ) {
       
  // 插入单元格
       
  NSIndexPath  *indexPath = [ NSIndexPath indexPathForRow : self . dataSource . count  -  1  inSection : 0 ];
       
  // 第一个参数 ,  插入单元格的 indexPath
       
  //    :  插入时的动画
        [
self . tableView  insertRowsAtIndexPaths : @[ indexPath ] withRowAnimation : UITableViewRowAnimationLeft ];
    }
else  if  ([change[ @"kind" ] integerValue ] == NSKeyValueChangeRemoval ){
       
  NSIndexSet  *set = change[ @"indexes" ];
       
  // 枚举集合中的每一个值  ( 当前 set 中永远为一个 )
       
  __block  NSIndexPath  *indexPath =  nil ;
        [set
  enumerateIndexesUsingBlock :^( NSUInteger  idx,  BOOL *stop) {
            indexPath = [
NSIndexPath  indexPathForRow :idx inSection : 0 ];
        }];
       
  // 删除单元格
        [
self . tableView  deleteRowsAtIndexPaths : @[ indexPath ] withRowAnimation : UITableViewRowAnimationFade ];
    }
else  if  ([change[ @"kind" ] integerValue ] ==  NSKeyValueChangeReplacement ){
       
  NSIndexSet  *set = change[ @"indexes" ];
       
  // 枚举集合中的每一个值  ( 当前 set 中永远为一个 )
       
  __block  NSIndexPath  *indexPath =  nil ;
        [set
  enumerateIndexesUsingBlock :^( NSUInteger  idx,  BOOL *stop) {
            indexPath = [
NSIndexPath  indexPathForRow :idx inSection : 0 ];
        }];
       
  // 更新单元格
        [
self . tableView  reloadRowsAtIndexPaths : @[ indexPath ] withRowAnimation : UITableViewRowAnimationFade ];
       
    }
}


//*  当我们观察  数组的变化时一定会要完成系统为我们生成的两个方法 ,  一个是 insert,  一个是 remove, 必须配对出现 ,  在该方法中完成数组的对应操作


- (
void )insertObject:( id )object inDataSourceAtIndex:( NSUInteger )index{
   
  // 向数组中插入数据
    [
self . dataSource  insertObject :object  atIndex :index];
}
// 系统动态生成的方法
- (
void )removeObjectFromDataSourceAtIndex:( NSUInteger )index{
    [
self . dataSource  removeObjectAtIndex :index];
}
// 系统为我们生成了一个修改方法
- (
void )replaceObjectInDataSourceAtIndex:( NSUInteger )index withObject:( id )object{
   
  // 在该方法中修改数组的元素
    [
self . dataSource  replaceObjectAtIndex :index withObject :object];
}
- (
void )didReceiveMemoryWarning {
    [
super  didReceiveMemoryWarning ];
   
  // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (
NSInteger )numberOfSectionsInTableView:( UITableView *)tableView {
   
  return  1 ;
}

- (
NSInteger )tableView:( UITableView  *)tableView numberOfRowsInSection:( NSInteger )section {
   
  return  self . dataSource . count ;
}


- (
UITableViewCell  *)tableView:( UITableView  *)tableView cellForRowAtIndexPath:( NSIndexPath  *)indexPath {
   
  UITableViewCell  *cell = [tableView  dequeueReusableCellWithIdentifier : @"cell"  forIndexPath :indexPath];
   
  // 取出模型
   
  Stock  *stock =  self . dataSource [indexPath. row ];
    cell.
textLabel . textColor  = [ UIColor colorWithRed : arc4random ()% 256 / 255.0  green : arc4random ()% 256 / 255.0 blue : arc4random ()% 256 / 255.0  alpha : 1 ];
    cell.
textLabel . text  = [ NSString  stringWithFormat : @"%@ -- %f" , stock. stockName , stock. price ];
   
   
  return  cell;
}
- (
void )tableView:( UITableView  *)tableView didSelectRowAtIndexPath:( NSIndexPath  *)indexPath{
   
  // 点击 cell 的时候修改对应 cell 的内容
   
  //1. 先修改数据源
   
  // 先找到模型
   
  Stock  *stock =  self . dataSource [indexPath. row ];
    stock.
stockName  =  @" 中石油 " ;
    [
self  replaceObjectInDataSourceAtIndex :indexPath. row withObject :stock];
}


// Override to support conditional editing of the table view.
- (
BOOL )tableView:( UITableView  *)tableView canEditRowAtIndexPath:( NSIndexPath  *)indexPath {
   
  return  YES ;
}
// Override to support editing the table view.
- (
void )tableView:( UITableView  *)tableView commitEditingStyle:( UITableViewCellEditingStyle )editingStyle forRowAtIndexPath:( NSIndexPath  *)indexPath {
   
  // 删除
   
  if  (editingStyle ==  UITableViewCellEditingStyleDelete ) {
       
  // 删除数据源
        [
self  removeObjectFromDataSourceAtIndex :indexPath. row ];
       
    }
// 插入
   
  else  if  (editingStyle ==  UITableViewCellEditingStyleInsert ) {
       
    }
}


@end

Stock.h


#import 

@interface Stock : NSObject
//股票的名字
@property (nonatomic, copy)NSString *stockName;
@property (nonatomic, assign)float price;//股票的价格
@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值