链式编程思想:通过点语法增加代码可读性
使用方法:设计一个类,定义类的一个对象方法(例如add),这个方法没有参数,返回值是一个block。(目的是可以用点语法和括号传参数,例如xxx.add(20) )返回值的block必须有参数和返回值,有参数的作用是可以在外面调用时传要计算的值进来,例如add(20)传了20进来,返回值必须是对象方法所在的类本身,目的是返回这个类之后可以继续调用对象方法,形成链式。
SYXCalculateMaker.h
//
// SYXCalculateMaker.h
// SYXBlockTest2
//
// Created by admin on 17/3/14.
// Copyright © 2017年 admin. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SYXCalculateMaker : NSObject
@property (nonatomic, assign) int result;
- (SYXCalculateMaker * (^)(int num))add;
@end
SYXCalculateMaker.m
#import "SYXCalculateMaker.h"
@implementation SYXCalculateMaker
- (SYXCalculateMaker *(^)(int num))add{
return ^(int num){
self.result += num;
return self;
};
}
@end
在外面调用
#import "ViewController.h"
#import "SYXCalculateMaker.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
SYXCalculateMaker *maker = [[SYXCalculateMaker alloc] init];
int output = [maker.add(10).add(50).add(808) result];
NSLog(@"%d", output);
}
@end
利用block实现高聚合代码(实现一个功能的代码都放在一起)
- 定义一个分类,使所有类都能直接调用
NSObject+SYXCalculator.h
#import <Foundation/Foundation.h>
#import "SYXCalculateMaker.h"
@interface NSObject (SYXCalculator)
+ (int) makeCalculation:(void(^)(SYXCalculateMaker *maker))block;
@end
NSObject+SYXCalculator.m
#import "NSObject+SYXCalculator.h"
@implementation NSObject (SYXCalculator)
+ (int)makeCalculation:(void (^)(SYXCalculateMaker *maker))block{
SYXCalculateMaker *maker = [[SYXCalculateMaker alloc] init];
// 执行block,相当于执行maker.add(10).add(xxx)... 此时结果已经在result中保存了
block(maker);
// 返回结果
return maker.result;
}
@end
使用这个方法实现计算代码高聚合
#import "ViewController.h"
#import "SYXCalculateMaker.h"
#import "NSObject+SYXCalculator.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// SYXCalculateMaker *maker = [[SYXCalculateMaker alloc] init];
//
// int output = [maker.add(10).add(50).add(808) result];
//
// NSLog(@"%d", output);
int number = [NSObject makeCalculation:^(SYXCalculateMaker *maker) {
maker.add(22).add(44);
maker.add(123).add(22).add(33);
maker.add(99).add(70);
}];
NSLog(@"%d", number);
}
@end