文章参考自
链式编程在一些三方库(Masonry)中广泛的应用,通过点语法,将方法连贯的执行下去。
定义一个person类,要求实现以下功能:
person.runBlock().studyBlock().runBlock(); person.studyBlock().studyBlock().runBlock();
具体实现:
@class Person;
typedef Person *(^PersonBlock)();
@interface Person : NSObject
- (PersonBlock)runBlock;
- (PersonBlock)studyBlock;
@end
- (PersonBlock)runBlock {
Person *(^block)() = ^(){
NSLog(@"Run Run Run");
return self;
};
return block;
}
- (PersonBlock)studyBlock{
Person *(^block)() = ^() {
NSLog(@"Study Study Study");
return self;
};
return block;
}
调用:
Person *person = [[Person alloc]init];
PersonBlock block1 = [person runBlock];
PersonBlock block2 = [block1() studyBlock];
block2();
可以尝试着再对block传入参数,实现可传参的链式编程。
网友评论