美文网首页程序员
RAC学习三(集合类RACTuple与RACSequence)

RAC学习三(集合类RACTuple与RACSequence)

作者: RM_乾笙 | 来源:发表于2018-05-30 17:32 被阅读5次

    RAC集合类

    1、RACTuple

    RACTuple的用法类似于OC里的数组用法,从源码来看像是NSArray的再封装,不过其宏使用比较多
    RACTuple的简单用法

    //RACTuple 元祖
    RACTuple *tuple = [RACTuple tupleWithObjects:@"aa",@"bb",@"cc",nil];
    NSLog(@"tuple:%@:tuple\n",tuple);
        
    NSString *str = tuple[0];
    NSLog(@"str:%@",str);
    
    //打印内容
    2018-05-30 16:52:39.456813+0800 RAC集合类[27128:963676] tuple:<RACTuple: 0x60000001f5b0> (
        aa,
        bb,
        cc
    ):tuple
    2018-05-30 16:52:39.456961+0800 RAC集合类[27128:963676] str:aa
    
    2、RACSequence
    RACSequence对数组进行遍历

    1.RAC对OC的数组和RACTuple元类进行分类的扩充,所以使用rac_sequence能够转换成RACSequence的对象
    2.订阅RACSequence的signal,可遍历所有元素,但因其内部实现是异步执行的,所以使用时需要注意时间顺序。

    //RAC集合
    NSArray *arr = @[@"111",@"222",@"333"];    
    RACSequence *sequence = [arr rac_sequence];
    // 遍历
    RACSignal *signal = [sequence signal];
    // 订阅信号
    [signal subscribeNext:^(id  _Nullable x) {
          NSLog(@"%@",x);
     }];
    
    //打印内容
    2018-05-30 17:10:31.968736+0800 RAC集合类[27389:980932] 111
    2018-05-30 17:10:31.969152+0800 RAC集合类[27389:980932] 222
    2018-05-30 17:10:31.969321+0800 RAC集合类[27389:980932] 333
    

    RACSequence对字典进行遍历

    NSDictionary *dict = @{@"name":@"Mr_zhang",@"age":@"19",@"level":@"3"};
        [dict.rac_sequence.signal subscribeNext:^(id  _Nullable x) {
            //RACTupleUnpack:解析元祖
            //RACTupleUnpack宏的参数和字典的结构相对应
            RACTupleUnpack(NSString *key, NSString *value) = x;
            NSLog(@"%@:%@",key,value);
        }];
    
    //打印内容
    2018-05-30 17:16:06.739404+0800 RAC集合类[27539:986340] name:Mr_zhang
    2018-05-30 17:16:06.739662+0800 RAC集合类[27539:986340] age:19
    2018-05-30 17:16:06.740151+0800 RAC集合类[27539:986340] level:3
    

    RACSequence将字典解析成模型

    //用法1
    NSArray *sources = @[@{@"name":@"Mr_zhang",@"age":@"24"},
                         @{@"name":@"Mr_Li",@"age":@"31"},
                         @{@"name":@"Mr_Wang",@"age":@"25"},
                         @{@"name":@"Mr_Lin",@"age":@"20"} ];
    NSMutableArray *mutaArr = [[NSMutableArray alloc] init];
    [sources.rac_sequence.signal subscribeNext:^(id  _Nullable x) {
        [mutaArr addObject:[PersonModel parseWithDictionary:x]];
    }];
    
    //用法2
    NSArray *arr = [[dictArr.rac_sequence map:^id _Nullable(NSDictionary *value) {
        return [PersonModel parseWithDictionary:value];
    }] array];
    

    相关文章

      网友评论

        本文标题:RAC学习三(集合类RACTuple与RACSequence)

        本文链接:https://www.haomeiwen.com/subject/vbpojftx.html