打算在项目中大面积使用RAC来开发,所以整理一些常用的实践范例和比较完整的api说明方便开发时随时查阅
声明式编程泛型Declarative programming
函数反应式编程是声明式编程的子编程范式之一
高阶函数
需要满足两个条件
- 一个或者多个函数作为输入。
- 有且仅有一个函数输出。
Objective-c里使用block作为函数
1 2 3 4 |
[array enumerateObjectsUsingBlock:^(NSNumber *number, NSUInteger idx, BOOL *stop) { NSLog(@"%@",number); }]; |
映射map
1 2 3 |
NSArray * mappedArray = [array rx_mapWithBlock:^id(id each){ return @(pow([each integerValue],2)); }]; |
过滤filter
1 2 3 |
NSArray *filteredArray = [array rx_filterWithBlock:^BOOL(id each){ return ([each integerValue] % 2 == 0); }] |
折叠fold
1 2 3 4 5 |
[[array rx_mapWithBlock:^id (id each){ return [each stringValue]; }] rx_foldInitialValue:@"" block:^id (id memo , id each){ return [memo stringByAppendingString:each]; }]; |
RAC中使用高阶函数
映射
1 2 3 4 5 6 7 8 9 10 11 12 13 |
NSArray *array = @[ @1, @2, <a href='http://www.jobbole.com/members/3'>@3</a> ]; RACSequence * stream = [array rac_sequence]; //RACSequence是一个RACStream的子类。 [stream map:^id (id value){ return @(pow([value integerValue], 2)); }]; //RACSequence有一个方法返回数组:array NSLog(@"%@",[stream array]); //避免污染变量的作用域 NSLog(@"%@",[[[array rac_sequence] map:^id (id value){ return @(pow([value integerValue], 2)); }] array]); |
过滤
1 2 3 |
NSLog(@"%@", [[[array rac_sequence] filter:^BOOL (id value){ return [value integerValue] % 2 == 0; }] array]); |