RAC集合及其他用法
2019-12-24 本文已影响0人
BigBossZhu
RAC集合类:
- RACTuple:元组,类似NSArray,用来包装值
- RACSequence:RAC中集合,用于替代NSArray,NSDictionary可以使用它快速遍历.
NSArray *arr = @[@"12",@"2121",@1];
NSDictionary *dic = @{@"name":@"zhangsan",@"age":@"15",@"height":@"165"};
RACTuple *tuple = [RACTuple tupleWithObjectsFromArray:arr];
NSLog(@"%@",tuple[0]);
//将集合转化为RACSequence集合
RACSequence *sequence = arr.rac_sequence;
RACSignal *singal = sequence.signal;
[singal subscribeNext:^(id x) {
NSLog(@"%@",x);
}];
//数组遍历.
[arr.rac_sequence.signal subscribeNext:^(id x) {
NSLog(@"常用写法%@",x);
}];
//字典遍历RACTuple元组包装相应key:value
[dic.rac_sequence.signal subscribeNext:^(id x) {
NSLog(@"%@",x);
}];
RAC开发中常见用法:
- 代替代理
- kvo
- 通知
- 监听事件
- 文本框改变
代码实现
//监听某个某个对象的方法是否调用:代理的rac另外一种实现
[[self.reaVIew rac_signalForSelector:@selector(didClickAction:)] subscribeNext:^(id x) {
NSLog(@"点击按钮,但无法传值,x:%@",x);
/*
点击按钮,但无法传值,x:<RACTuple: 0x60000039cea0> (
"<UIButton: 0x7fc888c13890; frame = (97 63; 46 30); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x600000197e20>>"
)
*/
}];
//替代kvo,需要手动导入另外的头文件默认没导入
[self.reaVIew rac_observeKeyPath:@"frame" options:NSKeyValueObservingOptionNew observer:nil block:^(id value, NSDictionary *change, BOOL causedByDealloc, BOOL affectedOnlyLastComponent) {
NSLog(@"frame属性发生改变");
}];
[[self.view rac_valuesForKeyPath:@"frame" observer:nil]subscribeNext:^(id x) {
NSLog(@"frame属性发生改变%@",x);
}];
//监听事件
UIButton *btn = [[UIButton alloc]init];
[[btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
NSLog(@"按钮点击了");
}];
[[[NSNotificationCenter defaultCenter]rac_addObserverForName:UIKeyboardWillShowNotification object:nil]subscribeNext:^(id x) {
NSLog(@"通知");
}];
//监听文本框
UITextField *textField = [[UITextField alloc]init];
[[textField rac_textSignal]subscribeNext:^(id x) {
NSLog(@"文本框改变");
}];