3.集合类
3.1 RACTuple——元组类,类似NSArray,用来包装值.
RACTuple *tuple = [RACTuple tupleWithObjectsFromArray:@[@"小红",@"小明",@"小小",@"Gai爷"]];
NSString * str = tuple[0];
NSLog(@"%@",str);
运行如图
3.2 RACSequence——RAC中的集合类,用于代替NSArray,NSDictionary,可以使用它来快速遍历数组和字典。
- ①遍历数组
NSArray *array = @[@"小红",@"小明",@"小小",@"Gai爷"];
[array.rac_sequence.signal subscribeNext:^(id _Nullable x) {
NSLog(@"%@",x);
}];
运行如图
- ②遍历字典
简单模式
NSDictionary *dict = @{
@"1":@"小明",
@"2":@"小红",
@"3":@"笑笑",
@"4":@"gai爷"
};
[dict.rac_keySequence.signal subscribeNext:^(id _Nullable x) {
NSLog(@"rac_keySequence ==%@",x);
}];
[dict.rac_sequence.signal subscribeNext:^(RACTwoTuple * x) {
NSLog(@"rac_sequence == %@ ++ %@",x[0],x[1]);
}];
运行如图:
添加宏RACTupleUnpack
@"1":@"小明",
@"2":@"小红",
@"3":@"笑笑",
@"4":@"gai爷"
};
// [dict.rac_keySequence.signal subscribeNext:^(id _Nullable x) {
// NSLog(@"rac_keySequence ==%@",x);
// }];
[dict.rac_sequence.signal subscribeNext:^(RACTwoTuple * x) {
NSLog(@"rac_sequence == %@ ++ %@",x[0],x[1]);
RACTupleUnpack(NSString * key,NSString * value) = x;
NSLog(@"%@ : %@",key,value);
}];
运行如图:
RACTupleUnpack
是不是和我的x[0],x[1]
一样
- ③字典转模型
KFC.h
#import <Foundation/Foundation.h>
@interface KFC : NSObject
@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *icon;
+ (instancetype)kfcWithDict:(NSDictionary *)dict;
@end
KFC.m
#import "KFC.h"
@implementation KFC
+ (instancetype)kfcWithDict:(NSDictionary *)dict {
KFC *kfc = [[KFC alloc]init];
[kfc setValuesForKeysWithDictionary:dict];
return kfc;
}
@end
SetViewController.m
NSString *pathStr = [[NSBundle mainBundle]pathForResource:@"kfc.plist" ofType:nil];
NSArray *array = [NSArray arrayWithContentsOfFile:pathStr];
NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count];
[array.rac_sequence.signal subscribeNext:^(NSDictionary * x) {
KFC *kfc = [KFC kfcWithDict:x];
NSLog(@"%@",kfc);
[arrayM addObject:kfc];
}];
我们首先要创建一个空数组,通过模型的一个类方法将我们接收到的数据转成模型,再保存到数组中。
当然还有更爽的方法,集合的映射:它会将一个集合中的所有元素都映射成一个新的对象!
NSString *pathStr = [[NSBundle mainBundle]pathForResource:@"kfc.plist" ofType:nil];
NSArray *array = [NSArray arrayWithContentsOfFile:pathStr];
//会将一个集合中的所有元素都映射成一个新的对象!
NSArray * arr = [[array.rac_sequence map:^id _Nullable(NSDictionary * value) {
//返回模型!!
return [KFC kfcWithDict:value];
}] array];
NSLog(@"%@",arr);