关于 ReactiveCocoa,首先需要了解三个概念:map,filter 和 fold。
Functional Programming with RXCollections
One of the key concepts of functional programming is that of a “higher-order function”.
Accordingto Wikipedia, a higher-order function is a function that satisfies these two conditions:
• It takes one or more functions as input.
• It outputs a function.
In Objective-C, we often use blocks as functions.
Use CocoaPods to install RXCollections in your project. In your application:didFinishLaunchingWithOptions: method,do some code,create the array first.
NSArray *array =@[@(1),@(2),@(3)];
Map:遍历
map(1,2,3)=>(1,4,9)
using RXCollections:
//map
NSArray *mappedArray = [array rx_mapWithBlock:^id(id each) {
return @(pow([each integerValue], 2));
}];
NSLog(@"%@",mappedArray);
common:
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:];
for (NSNumber *number in array) {
[mutableArray addObject:@(pow([number integerValue], 2))];
}
NSArray *mappedArray = [NSArray arrayWithArray:mutableArray];
Filter:过滤
Filtering a list just returns a new list containing all of the original entries,
minus the entries that didn’t return true from a test.
using RXCollections:
//filter
NSArray *filteredArray = [array rx_filterWithBlock:^BOOL(id each) {
return ([each integerValue]%2 == 0);
}];
NSLog(@"%@",filteredArray);
common:
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:];
for (NSNumber *number in array) {
if ([number integerValue]%2 == 0) {
[mutableArray addObject:number];
}
}
NSArray *filteredArray = [NSArray arrayWithArray:mutableArray];