block块的用法

来源:互联网 发布:淘宝卖家刷一单10元 编辑:程序博客网 时间:2024/06/05 20:23

block块有3种用法:1.block作为对象的属性,2.block作为方法的参数,3.block作为返回值!!!(扩展非常强!!)。
我们现在先来看看第一种用法:block作为对象的属性,好处是把block传给了person类,person对象回调了block块。
Person.h

@interface Person : NSObject/** block :ARC使用strong  非ARC copy  */@property(nonatomic, strong) void(^block)();@end

ViewController.m

#import "ViewController.h"#import "Person.h"@interface ViewController ()@property(strong, nonatomic)Person *p;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    //1.block作为对象的属性    Person *p = [[Person alloc] init];    //block -- inlineBlock    void(^ZBBlock)() = ^() {        NSLog(@"block");    };    p.block = ZBBlock;    _p = p;}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    self.p.block();}

第二种:block作为方法的参数,用处是ViewController回调了block代码块,Person对象可以往ViewCrotroller传值和传事件,类似代理。
Person.h

@interface Person : NSObject- (void)eat:(void(^)(NSString *))block;@endViewController.m#import "ViewController.h"#import "Person.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    //2.block作为方法的参数    Person *p = [[Person alloc] init];    [p eat:^(NSString *s) {        NSLog(@"爱吃%@", s);    }];}

第三种:block作为返回值。因为函数有返回值,所以可以用.语法调用方法。返回值是block。
Person.h

@interface Person : NSObject- (void(^)(int))run;@end    Person.m#import "Person.h"@implementation Person- (void (^)(int))run{    return ^(int m){        NSLog(@"哥们跑了%d米", m);    };}@end    ViewController.m#import "ViewController.h"#import "Person.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    //3.block作为返回值    Person *p = [[Person alloc] init];    p.run(300);}
原创粉丝点击