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

原文地址:https://www.cnblogs.com/thbbsky/p/4259902.html