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

posted @ 2015-01-29 14:58  曹县三胖暴打大猩猩  阅读(390)  评论(0编辑  收藏  举报