前的开关最为例子:
typedef enum : NSUInteger {
SwitchStateOff,//default
SwitchStateOn,
} SwitchState;
typedef void(^SBlockType)(SwitchState state);
@interface SwitchB : NSObject
@property(nonatomic,assign,readonly)SwitchState currentState;
@property(nonatomic,strong)SBlockType changeStateBlockHandle;
@end
声明中的changeStateBlockHandle属性就是保存回调代码。设置回调,只需要将此属性赋值就可。
@interface Room : NSObject
@property (strong, nonatomic) Light *lightA;
@property (strong, nonatomic) SwitchB *s;
@end
@implementation Room
- (instancetype)init
{
self = [super init];
if (self) {
self.lightA = [[Light alloc] init];
self.s = [[SwitchB alloc] init];
__weak __block Room * copy_self = self;//打破强引用循环,后续章节会展开讲解
self.s.changeStateBlockHandle = ^(SwitchState state)
{
if (state == SwitchStateOff)
{
[self.lightA turnOff];
}
else
{
[self.lightA turnOn];
}
};
}
return self;
}
@end
当开关的状态发生改变时,开关需要将自身状态反馈给使用者。当使用Block回调接口的组件时,需要将回调代码直接封装,赋值给组件响应的Block类型的属性即可。当状态改变时,封装的代码便被组件调用。