你真的会用block吗?
block作为对象的`属性`
block作为方法的`参数`
block作为`返回值` (扩展性特别强)
在强化一下:
1.block作为对象的属性
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
/* block 在arc下用strong就可以 非ARC下 copy */
/** block */
@property (nonatomic,copy) void(^block)();
@end
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
/** Person *p */
@property (nonatomic,strong) Person *p;
@end
- (void)viewDidLoad {
[super viewDidLoad];
Person *p = [[Person alloc] init];
void(^XDBlock)() = ^() {
NSLog(@"XDBlock");
};
//调用
// XDBlock();
p.block = XDBlock;
_p = p;
}
$NSLog:XDBlock
2.block 作为方法的参数
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (void)eat:(void(^)(NSString *))block;
@end
Person.m
@implementation Person
- (void)eat:(void (^)(NSString *))block{
block(@"😄");
}
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
/** Person *p */
@property (nonatomic,strong) Person *p;
@end
- (void)viewDidLoad {
[super viewDidLoad];
Person *p = [[Person alloc] init];
[p eat:^(NSString *a) {
//这里面的代码块就是传递的参数
NSLog(@"吃东西%@",a);
}];
}
$NSLog:吃东西😄
3.block作为返回值 (扩展性特别强)
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (void(^)(int))run;
@end
Person.m
@implementation Person
- (void(^)(int))run{
return ^(int m){
NSLog(@"跑了%d米",m);
};
}
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
/** Person *p */
@property (nonatomic,strong) Person *p;
@end
- (void)viewDidLoad {
[super viewDidLoad];
Person *p = [[Person alloc] init];
Person *p = [[Person alloc] init];
// [p run:3];
p.run(3);
}
$NSLog:2017-06-13 15:08:32.164 Block[30445:3119801] 跑了3米