您的位置:首页 > 其它

初识RAC:001--Block简单使用

2017-10-10 23:43 375 查看

1.新建一个Person类

.h文件中

#import <Foundation/Foundation.h>

@interface Person : NSObject

//0.block在ARC中试用Strong就行 在非ARC机制中试用Copy,block作为对象的属性
@property(nonatomic,strong) void(^CZGBlock)(void);//返回值、方法名、参数

//1.block作为方法的参数,()里面为参数的属性,block为参数名
- (void)eat:(void(^)(void))block;//无参数
- (void)run:(void(^)(int meter))runBlock;//有参数

//2.block作为返回值
- (void(^)(void))seelp;//无参数
- (void(^)(int mintune))seelp1;//有参数
@end

.m文件中
#import "Person.h"

@implementation Person

- (void)eat:(void(^)(void))block
{
block();//执行外面传进来的block方法
}

-(void)run:(void (^)(int))runBlock
{
runBlock([@"123" intValue]);//执行外面传进来的block方法,同时将方法的参数传出去外面
}

- (void (^)(void))seelp
{
return ^(){
NSLog(@"睡你麻痹,起来嗨");
};
}
-(void (^)(int))seelp1
{
return ^(int m){
NSLog(@"哥们你睡了%d分钟",m);
};
}
@end

2.ViewController中

.m中
#import "ViewController.h"
#import "Person.h"

@interface ViewController ()
@property(nonatomic,strong)Person *P;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Person *p = [[Person alloc]init];
self.P = p;
[self block0];
[self block1];
[self block2];
}

//0.block作为对象的属性,可将对象外的值赋值给对象
- (void)block0
{
//block -->inlineBlock
void(^CZGBlock)(void) = ^() {
NSLog(@"block运行");
};
//调用block
self.P.CZGBlock =  CZGBlock;
}

//1.block作为方法的参数
- (void)block1
{
[self.P eat:^{
NSLog(@"吃了");
}];

[self.P run:^(int meter) {
NSLog(@"run了%d米",meter);
}];
}

//2.block作为返回值
- (void)block2
{
self.P.seelp();
self.P.seelp1(123);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.P.CZGBlock();
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  block RAC初识-block