1.如何实现方法的连续调用,比如
[[DXPerson alloc] init];
新建DXPerson类
#import <Foundation/Foundation.h>
// 在这两个宏之间的代码,所有简单指针对象都被假定为nonnull
NS_ASSUME_NONNULL_BEGIN
@interface DXPerson : NSObject
// 1.用'[]'实现连续调用
- (DXPerson *)eat1;
- (DXPerson *)sleep1;
// 因此我们只需要去指定那些nullable的指针
//- (id)itemWithName:(nullable NSString *)name;
@end
NS_ASSUME_NONNULL_END
DXPerson.m实现
#import "DXPerson.h"
@implementation DXPerson
// 1.用'[]'实现连续调用
- (DXPerson *)eat1{
NSLog(@"%s",__FUNCTION__);
return self;
}
- (DXPerson *)sleep1{
NSLog(@"%s",__FUNCTION__);
return self;
}
实现示例
- (void)viewDidLoad {
[super viewDidLoad];
DXPerson *person = [[DXPerson alloc] init];
// 用'[]'实现连续调用
[[person eat1] sleep1];
}
2.如何实现函数式编程,比如
person.eat2();
DXPerson.h
// 2.函数式编程,用block实现
- (void (^)(void))eat2;
- (void (^)(void))sleep2;
DXPerson.m
// 2.函数式编程,用block实现
- (void (^)(void))eat2{
// 定义block
void (^eat2Block)(void) = ^{
NSLog(@"%s",__FUNCTION__);
};
return eat2Block;
}
- (void (^)(void))sleep2{
return ^{
NSLog(@"%s",__FUNCTION__);
};
}
3.如何实现实现函数式 + 链式(无参),比如
person.eat3().sleep3();
DXPerson.h
// 3.实现函数式 + 链式(无参)
- (DXPerson *(^)(void))eat3;
- (DXPerson *(^)(void))sleep3;
DXPerson.m
// 3.实现函数式 + 链式(无参)
- (DXPerson *(^)(void))eat3{
DXPerson *(^eat3Block)(void) = ^ {
NSLog(@"%s",__FUNCTION__);
return self;
};
return eat3Block;
}
//上下两种写法一样
- (DXPerson *(^)(void))sleep3{
return ^{
NSLog(@"%s",__FUNCTION__);
return self;
};
}
4.如何实现实现函数式 + 链式(带参),比如
person.eat4(@"面包").sleep4(5);
DXPerson.h
// 4.实现函数式 + 链式(带参)
- (DXPerson *(^)(NSString *foodName))eat4;
- (DXPerson *(^)(NSInteger hour))sleep4;
DXPerson.m
// 4.实现函数式 + 链式(带参)
- (DXPerson *(^)(NSString *foodName))eat4{
DXPerson *(^eat4Block)(NSString *foodName) = ^(NSString *foodName) {
NSLog(@"吃: %@",foodName);
return self;
};
return eat4Block;
}
- (DXPerson *(^)(NSInteger hour))sleep4{
DXPerson *(^sleep4Block)(NSInteger hour) = ^(NSInteger hour) {
NSLog(@"睡了%ld小时",hour);
return self;
};
return sleep4Block;
}
思考:什么情况下适合链式编程? 适合动态,可接收不在乎调用先后顺序,次数等动态需求
链式编程有什么好处? 提高开发效率
链式编程有什么弊端? 降低一些运行效率,但是可以忽略