美文网首页
iOS 封装一个链式编程的应用框架

iOS 封装一个链式编程的应用框架

作者: Onlyoner | 来源:发表于2017-06-19 19:44 被阅读0次

    写一个能够实现连加(乘除减类似)

     n.add(10).add(20).add(30);
     n = 60;
    

    首先写一个NSObject的分类,便于所有类都可调用:
    通过分析Masonry

    结构
    - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block;
    

    我们可以定义此方法为:

    + (int)rr_makeConstraints:(void(^)(SumManager *manager))block;
    
    SumManager就相当于MASConstraintMaker中的约束制造者
    在这里担任加法管理者
    

    SumManager.h

    #import <Foundation/Foundation.h>
    
    @interface SumManager : NSObject
    
    /**  */
    @property (nonatomic,assign) int result;
    
    - (SumManager * (^)(int value))add;
    
    @end
    
    

    SumManager.m

    #import "SumManager.h"
    
    @implementation SumManager
    
    - (SumManager * (^)(int value))add{
    
        return ^(int value){
        
            _result += value;
            
            return self;
            //返回一个“方法调用者”
        };
        
    }
    
    @end
    
    

    NSObject+Sum.h

    #import <Foundation/Foundation.h>
    #import "SumManager.h"
    @interface NSObject (Sum)
    
    + (int)rr_makeConstraints:(void(^)(SumManager *manager))block;
    
    @end
    

    NSObject+Sum.m

    #import "NSObject+Sum.h"
    
    @implementation NSObject (Sum)
    
    + (int)rr_makeConstraints:(void(^)(SumManager *manager))block{
    
        SumManager *mgr = [[SumManager alloc] init];
        
        block(mgr);
        
        return mgr.result;
        
    }
    
    @end
    

    正式使用:ViewController.m

    
    #import "ViewController.h"
    #import "NSObject+Sum.h"
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        int sum = [NSObject rr_makeConstraints:^(SumManager *manager) {
            
            manager.add(10).add(20).add(30);
            
        }];
        
        NSLog(@"sum == %d",sum);
        
        
    }
    
    
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    
    @end
    

    输出结果:

    2017-06-19 16:44:46.000 002-链式编程思想[3006:1593180] sum == 60
    
    

    相关文章

      网友评论

          本文标题:iOS 封装一个链式编程的应用框架

          本文链接:https://www.haomeiwen.com/subject/jvrnqxtx.html