创建Mother类和OldWoman类:
Mother.h中的代码:
#import <Foundation/Foundation.h>
@interface Mother : NSObject
@property(nonatomic, copy)NSString *name;
//block作为属性运用
@property(nonatomic,copy) void(^actionBlock)();
//block当参数传递
-(void)goOutsideWithAction:(void (^)())action;
-(void)cooking;
@end
#import "Mother.h"
@implementation Mother
-(void)goOutsideWithAction:(void (^)())action
{
NSLog(@"去上班了");
action();
}
-(void)cooking
{
NSLog(@"我去做饭了");
// self.actionBlock();
if(self.actionBlock) {
self.actionBlock();
}
}
@end
OldWoman.h中的代码:
#import <Foundation/Foundation.h>
@interface OldWoman : NSObject
-(void)lookAfterBaby;
@end
#import "OldWoman.h"
@implementation OldWoman
-(void)lookAfterBaby
{
NSLog(@"我帮你照顾宝宝");
}
@end
main.m中代码
#import <Foundation/Foundation.h>
#import "Mother.h"
#import "OldWoman.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Mother *mother = [[Mother alloc] init];
OldWoman *oldWoman = [[OldWoman alloc] init];
/*mother执行goOutsideWithAction方法后
通知oldWoman执行lookAfterBaby方法*/
[mother goOutsideWithAction:^{
[oldWoman lookAfterBaby];
}];
/*因为block作为属性自动生成setter和getter方法
mother可以直接执行setActionBlock方法然后
通知oldWoman执行lookAfterBaby方法*/
[mother setActionBlock:^{
[oldWoman lookAfterBaby];
}];
[mother cooking];
}
return 0;
}