1. 函数式编程
#import "Person.h"
@implementation Person
#pragma mark - 链式编程 -
-(Person *)eat{
NSLog(@"吃");
return self;
}
-(Person *)drink{
NSLog(@"喝");
return self;
}
#pragma mark - 函数式编程 -
-(Person *(^)())eat1{
Person * (^block)()=^{
NSLog(@"吃1");
return self;
};
return block;
}
//简便式写法
-(Person *(^)())drink1{
return ^(){
NSLog(@"喝1");
return self;
};
}
#pragma mark - 带有参数的函数式编程 -
-(Person *(^)(NSString *))eat2{
Person * (^block)(NSString * food) = ^(NSString * food){
NSLog(@"吃%@",food);
return self;
};
return block;
}
//简便写法
-(Person *(^)(NSString *))drink2{
return ^(NSString * drinkSth){
NSLog(@"喝%@",drinkSth);
return self;
};
}
@end
调用 Person * person = [[Person alloc]init];
person.eat2(@"包子").drink2(@"水");
2.函数式编程
#import <Foundation/Foundation.h>
#import "CalculateManager.h"
@interface CalculateManager : NSObject
/** 用来存放相加的结果 */
@property (nonatomic, assign) NSInteger result;
//返回值为一个CalculateManager *(^)(NSInteger)类型的block
- (CalculateManager *(^)(NSInteger))add;
+ (NSInteger)why_makeCalculate: (void(^)(CalculateManager *))block;
@end
@implementation CalculateManager
- (CalculateManager *(^)(NSInteger))add {
return ^(NSInteger value) {
_result += value;
return self;
};
}
+ (NSInteger)why_makeCalculate:(void(^)(CalculateManager *))block {
CalculateManager *manager = [[CalculateManager alloc] init];
block(manager);
return manager.result;
@end
调用
NSInteger value = [NSObject why_makeCalculate:^(CalculateManager *manager) {
manager.add(5).add(5).add(5).add(10);
}];
NSLog(@"%zd", value);
// - 防止循环引用 防止在代码块中 weakSelf 为nil
__weak typeof(self) weakSelf = self;
self.block = ^{
__strong typeof(self) strongSelf = weakSelf;
[strongSelf copy];
};