码迷,mamicode.com
首页 > 其他好文 > 详细

ReactiveCocoa(RAC)

时间:2016-07-12 23:00:02      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

好处:代码高聚合,方便我们管理;

编程思想:函数式响应编程;

链式编程:

CaculatorMaker.h

#import <Foundation/Foundation.h>
#define ADD
#define KVO
@interface CaculatorMaker : NSObject
@property (nonatomic, assign) KVO int result;
// +
- (instancetype)add:(int)num; ADD
- (CaculatorMaker *(^)(int num))add;
// -
// *
- (CaculatorMaker *(^)(int num))multy;
// /
@end

CaculatorMaker.m

#import "CaculatorMaker.h"
@implementation CaculatorMaker
//- (instancetype)add:(int)num
//{
//    _result += num;
//    return self;
//}
- (CaculatorMaker *(^)(int))multy
{
    return ^(int num){
        _result *= num;
        return self;
    };
}
- (CaculatorMaker * (^)(int num))add
{
    return ^(int num){
        _result += num;
        return self;
    };
}
@end

NSObject+Caculator.h

#import <Foundation/Foundation.h>
#import "CaculatorMaker.h"
@interface NSObject (Caculator)
// 以后计算都使用这个方法,一调用这个方法就返回结果.
+ (int)makeCaculator:(void(^)(CaculatorMaker *))block;
@end

NSObject+Caculator.m

#import "NSObject+Caculator.h"
#import "CaculatorMaker.h"
@implementation NSObject (Caculator)
+ (int)makeCaculator:(void (^)(CaculatorMaker *))block
{
    // 创建计算制造者
    CaculatorMaker *maker = [[CaculatorMaker alloc] init];
    // 计算
    block(maker);
    return maker.result;
}
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    // add(1).add(2)
    // 1.创建计算制造者
    CaculatorMaker *maker = [[CaculatorMaker alloc] init];
    // 10 + 20 + 30 + 40
    // 链式编程思想: maker.add(10).add(20).add(30).add(40)
//   int result = [maker.add(10).add(20).add(30).add(40) result];
    // 提供一个没参数的add方法,返回值block
//   int reslut = [[[[[maker add:10] add:20] add:30] add:40] result];
    // block:使代码高聚合
    int result = [NSObject makeCaculator:^(CaculatorMaker *maker) {
        // 把所有的计算代码封装到这里
        maker.add(10).add(20);
        maker.add(30).add(40);
        maker.multy(3);
    }];
    NSLog(@"%d",result);
}

 

ReactiveCocoa(RAC)

标签:

原文地址:http://www.cnblogs.com/jingdizhiwa/p/5665097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!