我以前的kvo NSMutableArray,调用add不够优雅
//www.greatytc.com/p/47f766ec60a2
现在利用ReactiveObjC的rac_signalForSelector,调用add很优雅(原理利用aop)
使用
- 监听
__weak typeof(self) weakSelf = self;
[self.dataArray ax_addKVO:^(NSMutableArray * _Nonnull array) {
__strong typeof(weakSelf) strongSelf = weakSelf;
NSLog(@"strongSelf.dataArray = %@",strongSelf.dataArray);
NSLog(@"array = %@",array);
}];
- 添加
[self.dataArray addObject:@"2"];
代码
添加 NSMutableArray 分类
- .h文件
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSMutableArray (AXKVO)
/// NSMutableArray 监听方法
/// @param handler 回调
-(void)ax_addKVO:(void(^)(NSMutableArray *array))handler;
@end
NS_ASSUME_NONNULL_END
- .m文件,还有很多方法,自行添加
#import "NSMutableArray+AXKVO.h"
#import <ReactiveObjC/ReactiveObjC.h>
@implementation NSMutableArray (AXKVO)
-(void)ax_addKVO:(void(^)(NSMutableArray *array))handler{
/// add
[self _ax_addSelector:@selector(addObject:) handler:handler];
/// set
[self _ax_addSelector:@selector(setObject:atIndexedSubscript:) handler:handler];
/// insert
[self _ax_addSelector:@selector(insertObject: atIndex:) handler:handler];
[self _ax_addSelector:@selector(insertObject: atIndex:) handler:handler];
///replace
[self _ax_addSelector:@selector(replaceObjectAtIndex: withObject:) handler:handler];
/// remove
[self _ax_addSelector:@selector(removeLastObject) handler:handler];
[self _ax_addSelector:@selector(removeObject:) handler:handler];
[self _ax_addSelector:@selector(removeAllObjects) handler:handler];
[self _ax_addSelector:@selector(removeObjectAtIndex:) handler:handler];
}
-(void)_ax_addSelector:(SEL)selector handler:(void(^)(NSMutableArray *array))handler{
__weak typeof(self) weakSelf = self;
[[self rac_signalForSelector:selector] subscribeNext:^(id _Nullable x) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (handler) {
handler(strongSelf);
}
}];
}
@end