iOS默认不支持对数组的KVO,
KVO监听的是一个属性的指针变化
因为普通方式监听的对象的地址的变化,
而数组内部元素发送变化,数组对应的指针没有变化, 而是里面的值发生了改变。这就导致为什么使用普通的添加方法KVO监听不到变化
@interface ArrayModel : NSObject
@property (strong,nonatomic)NSMutableArray *voiceStrArray;
@end
@implementation ArrayModel
-(NSMutableArray *)voiceStrArray{
if(!_voiceStrArray){
_voiceStrArray = [NSMutableArray array];
}
return _voiceStrArray;
}
@end
@interface VoicePlayHelper (){
}
@property (nonatomic, strong)ArrayModel *arrayModel;
@end
@implementation VoicePlayHelper
+ (VoicePlayHelper *)sharedInstance{
static dispatch_once_t onceToken;
static VoicePlayHelper *_notiCenter = nil;
dispatch_once(&onceToken,^{
_notiCenter = [[super allocWithZone:NULL] init];
});
return _notiCenter;
}
+ (id)allocWithZone:(struct _NSZone *)zone{
return [self sharedInstance];
}
#pragma - implement NSCopying
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)init
{
if ((self=[super init]))
{
arrCount = 1;
[self addObserver];
}
return self;
}
- (void)dealloc {
[_arrayModel removeObserver:self forKeyPath:@"voiceStrArray" context:NULL];
}
- (void)addObserver
{
_arrayModel = [ArrayModel new];
[_arrayModel addObserver:self forKeyPath:@"voiceStrArray" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"%@",change);
//一旦key值对应的value改变,
if ([keyPath isEqualToString:@"voiceStrArray"]) {
NSLog(@"数组发生变化:变成%lu个",(unsigned long)_arrayModel.voiceStrArray.count);
if (_arrayModel.voiceStrArray.count > 0 ) {
}
}
}