RACTuple
-
可用下标访问元素 (实现了objectAtIndexedSubscript:方法)
-
可用for in枚举(遵循NSFastEnumeration协议)
-
可跟NSArray互相转换
-
可转换为RACSequence
-
可把NSNull.null转为RACTupleNil.tupleNil
-
只从RACTuple的源码上看,貌似只是NSArray的再封装,并没有发现特别有用的地方,但可能在RAC的其他文件里面有特殊用途
-
RACTuple的简单使用方式:
//普通创建
RACTuple *tuple1 = [RACTuple tupleWithObjects:@1, @2, @3, nil];
RACTuple *tuple2 = [RACTuple tupleWithObjectsFromArray:@[@1, @2, @3]];
RACTuple *tuple3 = [[RACTuple alloc] init];
//宏创建
RACTuple *tuple4 = RACTuplePack(@1, @2, @3, @4);
//解包(等号前面是参数定义,后面是已存在的Tuple,参数个数需要跟Tuple元素相同)
RACTupleUnpack(NSNumber * value1, NSNumber * value2, NSNumber * value3, NSNumber * value4) = tuple4;
NSLog(@"%@ %@ %@ %@", value1, value2, value3, value4);
//元素访问方式
NSLog(@"%@", [tuple4 objectAtIndex:1]);
NSLog(@"%@", tuple4[1]);
RACSequence
- 继承于RACStream,也就是说具有跟RACSignal一样的Operation方法(map、filter等)
- 可用for in枚举(遵循NSFastEnumeration协议)
- RAC对OC的集合和RACTuple进行Category扩充,因此可用“集合.rac_sequence”,把集合快速转换成RACSequence对象
- 订阅RACSequence的signal,可遍历所有元素,但因为内部实现是异步执行的(for in是在当前线程),所以使用时候需要注意时间顺序。
NSArray *array = @[@1, @2, @3];
NSDictionary *dict = @{@"key1" : @"value1", @"key2" : @"value2", @"key3" : @"value3"};
NSString *str = @"ABC";
NSSet *set = [NSSet setWithArray:array];
RACTuple *tuple = [RACTuple tupleWithObjectsFromArray:array];
//NSArray 会返回元素
[array.rac_sequence.signal subscribeNext:^(id _Nullable x) {
NSLog(@"array rac_sequence : %@", x);
}];
//NSDictionary 会返回打包成Tuple的key、value
[dict.rac_sequence.signal subscribeNext:^(id _Nullable x) {
NSLog(@"dict rac_sequence : %@", x);
}];
//NSString 会返回单个字符
[str.rac_sequence.signal subscribeNext:^(id _Nullable x) {
NSLog(@"str rac_sequence : %@", x);
}];
//NSSet 会返回元素
[set.rac_sequence.signal subscribeNext:^(id _Nullable x) {
NSLog(@"set rac_sequence : %@", x);
}];
//RACTuple 会返回内置数组的元素
[tuple.rac_sequence.signal subscribeNext:^(id _Nullable x) {
NSLog(@"tuple rac_sequence : %@", x);
}];
//以下是输出结果,从结果可以看出,结果是乱序的
//如果再打印当前线程,会发现每种集合都在各自的一条线程上输出,但非主线程
//array rac_sequence : 1
//array rac_sequence : 2
//array rac_sequence : 3
//str rac_sequence : A
//set rac_sequence : 3
//str rac_sequence : B
//tuple rac_sequence : 1
//set rac_sequence : 2
//dict rac_sequence : <RACTuple: 0x610000004cf0> (key1,value1)
//tuple rac_sequence : 2
//str rac_sequence : C
//set rac_sequence : 1
//dict rac_sequence : <RACTuple: 0x610000004ce0> (key3,value3)
//tuple rac_sequence : 3
//dict rac_sequence : <RACTuple: 0x608000004bb0> (key2,value2)
网友评论