您的位置:首页 > 其它

KVO监听数组的变化

2015-01-29 14:58 309 查看
#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


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: