在RAC中可以使用RACSequence,来进行对数组以及字典的快速便利
1、RAC对字典进行遍历
NSDictionary *dict = @{@"user":@"admin",@"age":@"20",@"gender":@"man"};
RACSequence *sequence = dict.rac_sequence;
RACSignal *signal = sequence.signal;
[signal subscribeNext:^(id x) {
//进行对数据的处理,如下
}];
//可以将上述代码转换如下
[dict.rac_sequence.signal subscribeNext:^(id x) {
RACTupleUnpack(NSString *key,NSString *value) = x;
NSLog(@"%@-%@",key,value);
}];
对字典遍历出来的结果是元组
2016-05-26 10:25:21.335 RACSquence[3323:74315] <RACTuple: 0x7ff610e0a6f0> (
age,
20
)
其中RACTupleUnpack是一个宏,用来解析元组。
他需要的参数就是 键、值,右边的x就是你需要进行处理的元组了。
2、RAC对数组进行遍历
NSString *path = [[NSBundle mainBundle]pathForResource:@"data.plist" ofType:nil];
NSArray *array = [[NSDictionary dictionaryWithContentsOfFile:path]objectForKey:@"data"];
NSMutableArray *dataSource = [NSMutableArray array];
[array.rac_sequence.signal subscribeNext:^(NSDictionary *x) {
Model *model = [Model modelWithDict:x];
[dataSource addObject:model];
NSLog(@"%@",model.date_week);
}];
其中的array结构如下
Model是一个数据模型
import <Foundation/Foundation.h>
@interface Model : NSObject
@property (nonatomic,copy)NSString *rise_and_fall_rate;
@property (nonatomic,strong)NSNumber* avg5;
@property (nonatomic,strong)NSNumber* avg20;
@property (nonatomic,strong)NSNumber* low_px;
@property (nonatomic,strong)NSNumber* total_value_trade;
@property (nonatomic,strong)NSNumber* avg10;
@property (nonatomic,copy)NSString * date;
@property (nonatomic,strong)NSNumber* pre_close_px;
@property (nonatomic,strong)NSNumber* open_px;
@property (nonatomic,strong)NSNumber* close_px;
@property (nonatomic,strong)NSNumber* total_volume_trade;
@property (nonatomic,strong)NSNumber* high_px;
@property (nonatomic,strong)NSNumber* rise_and_fall_value;
@property (nonatomic,copy)NSString * date_week;
+(instancetype)modelWithDict:(NSDictionary *)dcit;
@end
.m
#import "Model.h"
@implementation Model
+(instancetype)modelWithDict:(NSDictionary *)dcit{
Model *model = [[self alloc]init];
[model setValuesForKeysWithDictionary:dcit];//使用KVC进行字典与模型的转换
return model;
}
@end
RAC对数组进行遍历的高级用法
//高级用法
NSArray *arr = [[array.rac_sequence map:^id(NSDictionary* value) {
// value是集合中的元素
// id返回对象就是映射的值
return [Model modelWithDict:value];
}]array];
NSLog(@"%@",arr);