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

Block实现链式编程

时间:2016-01-13 00:35:19      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

1.Person.h文件

#import <Foundation/Foundation.h>
@class Dog;
@interface Person : NSObject
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) float weight;
@property (strong, nonatomic) Dog *dog;
- (Person *(^)(void))run;
- (Person *(^)(void))eat;

- (Person *)go;
- (Person *)drink;
@end

2.Person.m文件中

#import "Person.h"

@implementation Person
- (Person *(^)(void))run {
    return ^(void){
        self.weight -=1;
        return self;
    };
}

- (Person *(^)(void))eat {
    return ^(void){
        self.weight +=1;
        return self;
    };
}

- (Person *)go{
    self.weight -=1;
    return self;
}

- (Person *)drink {
    self.weight +=1;
    return self;
}
@end

3.主函数中(main.m)

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Person.h"
#import "Dog.h"

int main(int argc, char * argv[]) {
    
    Person *person = [[Person alloc] init];
    person.name = @"小明";
    person.weight = 130;
    person.run().eat().eat().eat();
    NSLog(@"%f", person.weight);
    
    [[[[person run] eat] eat] eat];
    NSLog(@"%f", person.weight);
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
       
    }
}

Block实现链式编程

标签:

原文地址:http://www.cnblogs.com/JM110/p/5126008.html

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