ReactiveCocoa有关集合类的使用

时间:2022-01-12 14:49:27

Sequences 集合  表示一个不可变的序列值且不能包含空值,

1.实现NSArray的快速遍历

NSArray *numbers = @[@1, @2, @3, @4, @5, @6];

//通过rac_sequence来获取Signal

RACSignal *signal = numbers.rac_sequence.signal;

[signal subscribeNext:^(id x) {

//子线程异步请求

NSLog(@"%@", x);

}];

2.实现NSSet的快速遍历

NSSet *set = [NSSet setWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", nil];

RACSignal *setSignal = set.rac_sequence.signal;

[setSignal subscribeNext:^(id  _Nullable x) {

NSLog(@"%@", x);

}];

3.实现NSDictionary的快速遍历

NSDictionary *dict = @{@"key1":@"Hello", @"key2":@"World"};

RACSignal *dictSignal = dict.rac_sequence.signal;

[dictSignal subscribeNext:^(id x) {

NSLog(@"%@", x);

//可以看到x打印出来的是RACTuple对象 RACTuple 元组,使用RACTupleUnpack进行解包

RACTupleUnpack(NSString *key, NSString *value) = x;

NSLog(@"key = %@, value = %@", key, value);

}];

4.针对项目中经常遇到的结构复杂的数据结构中的相同模型转成model

使用rac中的map进行型号传递时的转换

@interface Person : NSObject

@property(nonatomic, strong)NSString *name;

@property(nonatomic, assign)NSInteger sex;

+ (instancetype)personWithDict:(NSDictionary *)dict;

@end

NSArray *personArray = @[@{@"name":@"小张", @"sex":@1}, @{@"name":@"小王", @"sex":@2}];

NSArray *resultArray = [[dictSignal2 map:^id(id value) {

return [Person personWithDict:value];

}] toArray];

NSLog(@"resultArray = %@", resultArray);