zoukankan      html  css  js  c++  java
  • KVO监听数组的变化

    #import "ViewController.h"
    
    @interface ViewController ()
    
     @property(nonatomic,strong)NSMutableArray *dataArray;
    
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        _dataArray=[NSMutableArray array];
        [self addObserver:self forKeyPath:@"dataArray" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    }
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
       
    }
    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
     
        if ([keyPath isEqualToString:@"dataArray"])
        {
             NSLog(@"---change=%@---",change);
            NSLog(@"dataArray.count=%ld",_dataArray.count);
        }
        
    }
    
    //添加
    - (IBAction)addBtnClick:(UIButton *)sender
    {
        [[self mutableArrayValueForKeyPath:@"dataArray"] addObject:@"3"];
        
    }
    //移除
    - (IBAction)deleteBtnClick:(UIButton *)sender
    {
        [[self mutableArrayValueForKeyPath:@"dataArray"] removeObject:@"3"];
        
        
    }
    -(void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(void *)context
    {
        [self removeObserver:self forKeyPath:@"dataArray" context:context];
    }
    
    -(void)insertObject:(id)object inDataArrayAtIndex:(NSUInteger)index
    {
        [self.dataArray insertObject:object atIndex:index];
    }
    -(void)removeObjectFromDataArrayAtIndex:(NSUInteger)index
    {
        [self.dataArray removeObjectAtIndex:index];
    }
    
    @end

  • 相关阅读:
    蚁群算法(AntColonyOptimization,ACO)与TSP问题
    EASY-X
    扩展欧几里得
    堆,set,优先队列
    单链表的几个基本操作
    剑指offer JZ-20
    剑指offer JZ-19
    拉普拉斯机制下的差分隐私(1)
    剑指offer JZ-17
    剑指offer JZ-16
  • 原文地址:https://www.cnblogs.com/thbbsky/p/4259902.html
Copyright © 2011-2022 走看看