Block介绍
- Block是一个匿名的函数代码块,此代码块可以当做参数传给其他对象。
- Block与代理协议的功能一样,都是用于对象通信的。
Block语法定义
*Block变量定义: 返回值(^变量名)(函数参数...)
int (^myBlocks)(int);
*Block函数的创建
myBlocks = ^(int a){
int result = a * a;
return result;
}
*Block函数的调用
int ret = myBlocks(10);
- block是一个匿名函数代码块
1>block声明的时候,就是传值的时候,代码块并没有被运行
2>在block回调的时候代码块才被执行 - typedef对block类型进行重命名(参数类型和返回值类型,以及有无参数,有无返回值,都会造成block类型)
typedef int (^MathBlock)(int, int);
MathBlock mulBlock;
mulBlock = ^(int a, int b){
return a * b;
};
NSLog(@"a*b = %d", mulBlock(2, 3));
Block实现对象间通信(保姆与小孩问题)
小孩类:
#import <Foundation/Foundation.h>
@interface Child : NSObject
typedef void(^HandleChildBlock)(Child *);
//小孩的清洁值
@property(nonatomic, assign)NSInteger cleanValue;
//Block的内存管理方式用copy
@property(nonatomic, copy)HandleChildBlock washBlock;
@end
#import "Child.h"
@implementation Child
- (instancetype)init
{
self = [super init];
if (self) {
_cleanValue = 100;
//定时器,循环调用方法,清洁值减少
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(timerAction:)
userInfo:nil
repeats:YES];
}
return self;
}
- (void)timerAction:(NSTimer *)timer {
NSLog(@"cleacValue:%lu", _cleanValue);
_cleanValue--;
if (_cleanValue == 95) {
//当清洁值为95时,保姆给小孩洗澡
if (self.washBlock) {
_washBlock(self);
}
}
}
@end
保姆类:
#import <Foundation/Foundation.h>
@class Child;
@interface Nanny : NSObject
- (void)washChild:(Child *)child;
@end
#import "Nanny.h"
#import "Child.h"
@implementation Nanny
- (void)washChild:(Child *)child {
child.washBlock = ^(Child *ch){
//Block代码块
NSLog(@"保姆给小孩洗澡");
ch.cleanValue = 100;
};
}
@end