iOS-链式编程

函数式编程------->链式编程

函数式编程:

#import "Person.h"

@implementation Person

- (void)eat:(NSString*)doSomething{
    NSLog(@"Today %@ %@",NSStringFromSelector(_cmd),doSomething);
}

- (void)run:(NSString*)doSomething{
    NSLog(@"Today %@ %@",NSStringFromSelector(_cmd),doSomething);
}

调用方式

Person* person = [Person new];
[person eat:@"fish"];
[person run:@"10km"];

我们最终目的是将函数式编程转换为链式编程:
首先将调用方式转换为

[[person eat:@"fish"] run:@"10km"];

要想调用完eat函数后继续调用run函数,则eat函数需返回当前对象。
修改后函数:

- (Person* )eat:(NSString*)doSomething{
    NSLog(@"Today %@ %@",NSStringFromSelector(_cmd),doSomething);
    return self;
}

- (Person* )run:(NSString*)doSomething{
    NSLog(@"Today %@ %@",NSStringFromSelector(_cmd),doSomething);
    return self;
}

此时仍为函数式调用
下一步将函数式转换为链式,如何采用()的方式传参,需要使用OC中block,点语法返回需要调用的block,调用时即可采用()方式传参。同时设置block的返回值为当前对象,即可实现链式编程。

#import 
@class Person;
typedef Person* (^RunBlock) (NSString* doSomething);

@interface Person : NSObject

- (RunBlock)eat;
- (RunBlock)run;
@end
#import "Person.h"

@implementation Person

- (RunBlock)eat{
    RunBlock block = ^(NSString* doSomething){
        NSLog(@"Today %@ %@",NSStringFromSelector(_cmd),doSomething);
        return self;
    };
    return block;
}

- (RunBlock)run{
    RunBlock block = ^(NSString* doSomething){
        NSLog(@"Today %@ %@",NSStringFromSelector(_cmd),doSomething);
        return self;
    };
    return block;
}
@end

调用方法

person.eat(@"fish").run(@"10km");

你可能感兴趣的:(iOS-链式编程)