@interface KvoOperation : NSOperation
@property (nonatomic, getter=isFinished) BOOL finished;
@property (nonatomic, strong) NSString *k;
@property (nonatomic, strong) NSMutableArray *mutArr;
-(void)insertObject:(id)object inMutArrAtIndex:(NSInteger)index;
@end
@implementation KvoOperation
@synthesize finished = _finished;
@synthesize k = _k;
@synthesize mutArr = _mutArr;
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
return NO;
}
- (void)setK:(NSString *)k {
[self willChangeValueForKey:@"k"];
_k = k;
[self didChangeValueForKey:@"k"];
}
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
-(void)insertObject:(id)object inMutArrAtIndex:(NSInteger)index {
[self willChange:(NSKeyValueChangeInsertion) valuesAtIndexes:[NSIndexSet indexSetWithIndex:index] forKey:@"mutArr"];
[_mutArr insertObject:object atIndex:index];
[self didChange:NSKeyValueChangeInsertion valuesAtIndexes:[NSIndexSet indexSetWithIndex:index] forKey:@"mutArr"];
}
@end
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key 返回 NO 可以屏蔽原生 set 方法出发的kvo监听,但是对于手动实现的kvo无效。
非集合类型手动触发 kvo :willChangeValueForKey:、didChangeValueForKey: ,不受automaticallyNotifiesObserversForKey: 屏蔽
集合类型(eg NSMutableArray)增、删、替换item不能触发kvo,如果用mutableArrayValueForKey:获取mArr,增、删、替换item 可触发kvo,且受automaticallyNotifiesObserversForKey:方法屏蔽作用
NSMutableArray *mArr = [_kvoOption mutableArrayValueForKey:@"mutArr"];
[mArr addObject:@"a"];
集合类型增、删、替换 item 手动触发kvo :例如插入时候调用下面方法,可触发kvo,不受automaticallyNotifiesObserversForKey: 屏蔽
-(void)insertObject:(id)object inMutArrAtIndex:(NSInteger)index {
[self willChange:(NSKeyValueChangeInsertion) valuesAtIndexes:[NSIndexSet indexSetWithIndex:index] forKey:@"mutArr"];
[_mutArr insertObject:object atIndex:index];
[self didChange:NSKeyValueChangeInsertion valuesAtIndexes:[NSIndexSet indexSetWithIndex:index] forKey:@"mutArr"];
}
Mark:NSOperation finished 属性为只读,这里重写,通过手动触发finished kvo,达到触发 completionBlock 目的
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)