实现iOS中的链式编程

谈到链式编程,那Masonry几乎就是最经典的代表.如:

make.top.equalTo(self.view).offset()

像这样top.equalTo(self.view).offset(60)通过”点”语法,将需要执行的代码块连续的书写下去,就是链式编程.它能使代码简单易读,书写方便


1.传统写法,两个方法需要单独调用,也不能任意组合顺序

创建Person类

Person.h:

- (void)eat1;
- (void)sleep1;
Person.m:

- (void)eat1
{
NSLog(@"%s",__FUNCTION__);
}
- (void)sleep1
{
NSLog(@"%s",__FUNCTION__);
}

控制器中调用Person类中方法

ViewController.m:

Person *person = [[Person alloc] init];
[person eat1];
[person sleep1];

2.用’[]’实现连续调用

Person.h:

- (Person *)eat2;
- (Person *)sleep2;
Person.m:

- (Person *)eat2
{
NSLog(@"%s",__FUNCTION__);
return self;
}
- (Person *)sleep2
{
NSLog(@"%s",__FUNCTION__);
return self;
}
ViewController.m:

[[person eat2] sleep2];
[[person sleep2] eat2];
 

3.用block实现链式

//person.eat3相当于get方法(很妙的自己可以试一下)

Person.h:

- (void (^)())eat3;
- (void (^)())sleep3;
Person.m:

- (void (^)())eat3
{
//定义block
void (^eat3Block)() = ^ {
NSLog(@"%s",__FUNCTION__);
};
return eatBlock;
}
- (void (^)())sleep3
{
return ^ {
NSLog(@"%s",__FUNCTION__);
};;
}
ViewController.m:

person.eat3();
person.sleep3();
 

4.实现 链式(无参)

Person.h:

- (Person * (^)())eat4;
- (Person * (^)())sleep4;
Person.m:

- (Person *(^)())eat4
{
Person * (^eat4Block)() = ^ {
NSLog(@"%s",__FUNCTION__);
return self;
};
return eat4Block;
}
//上下两种写法一样
- (Person *(^)())sleep4
{
return ^ {
NSLog(@"%s",__FUNCTION__);
return self;
};
}
ViewController.m:

person.eat4().sleep4();
person.sleep4().eat4();

5.实现 链式(带参)

//person.eat3相当于get方法(很妙的自己可以试一下) 返回值是block  调用block需要传参数 int  调用block返回值是对象本身

Person.h:

- (Person * (^)(NSString *foodName))eat5;
- (Person * (^)(NSInteger hour))sleep5;
Person.m:

- (Person *(^)(NSString *))eat5
{
Person * (^eat5Block)() = ^(NSString *foodName) {
NSLog(@"吃: %@",foodName);
return self;
};
return eat5Block;
}
//上下两种写法一样
- (Person *(^)(NSInteger))sleep5
{
return ^(NSInteger hour) {
NSLog(@"睡了%ld小时",(long)hour);
return self;
};
}
ViewController.m:

person.eat5(@"蛋糕").sleep5();
person.sleep5().eat5(@"面包");



 
上一篇:hdu4940 Destroy Transportation system(2014多校联合第七场)


下一篇:Ubuntu 14.0操作系统,修改默认打开方式的方法