1.新建一个空的project,在project中随便创建一个类,比方:
.h文件
#import <UIKit/UIKit.h>
typedef void(^resultBlock)(void);
@interface MyView : UIView
//回调函数的声明
@property (assign, nonatomic)resultBlock block;
//回调函数的实如今调用端实现
- (void)doSomething:(NSString *)string withTheBlock:(resultBlock)block;
@end
.m文件
#import "MyView.h"
@implementation MyView
- (void)doSomething:(NSString *)string withTheBlock:(resultBlock)block
{
self.block = block;
NSLog(@"string:%@",string);
if (self.block) {
self.block();
}
}
@end
2.在ViewController中实现
- (void)viewDidLoad {
[super viewDidLoad];
MyView *view = [[MyView alloc]init];
[view doSomething:@"Hello" withTheBlock:^{
NSLog(@"这里是回调");
}];
}
这样就实现了调用MyView对象的一个方法结束后。调用ViewController类中的方法。
时间: 2024-10-17 01:40:11