ios回调函数的标准实现:protocol+delegate
一、项目结构
二、主要代码
1、CoreManage.h
#import <Foundation/Foundation.h> @protocol SampleProtocol; //声明核心类的属性和方法 @interface CoreManage : NSObject @property(nonatomic,assign) id<SampleProtocol> delegate; - (void)doMainWork; @end //声明协议中的接口函数 @protocol SampleProtocol <NSObject> @required - (void)innerTaskCallBack:(int) innerTaskSerialNo; @optional - (void)resultDisplayCallBack:(NSString *)backInfo; @end
2、CoreManage.m
#import "CoreManage.h" @implementation CoreManage @synthesize delegate=_delegate; - (id)init { self = [super init]; if (self) { //初始化代码 } return self; } - (void)doMainWork { NSLog(@"核心类完成工序0"); NSLog(@"核心类完成工序1"); [self.delegate innerTaskCallBack:2];//工序2通过外部类回调函数完成 NSLog(@"核心类完成工序3"); [self.delegate resultDisplayCallBack:@"成功"];//通过外部类回调函数显示任务完成结果 } @end
3、OuterClass.h
#import <Foundation/Foundation.h> #import "CoreManage.h" @interface OuterClass : NSObject<SampleProtocol> - (void)run; @end
4、OuterClass.m
#import "OuterClass.h" @implementation OuterClass - (void)run { CoreManage *coreManage=[[CoreManage alloc] init]; coreManage.delegate=self; [coreManage doMainWork]; } //回调函数1 - (void)innerTaskCallBack:(int) innerTaskSerialNo{ NSLog(@"外部类的回调函数,完成工序%d",innerTaskSerialNo); } //回调函数2 - (void)resultDisplayCallBack:(NSString *)backInfo{ NSLog(@"外部类的回调函数,输出完成结果:%@",backInfo); } @end
5、AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; OuterClass *outerClass=[[OuterClass alloc]init]; [outerClass run]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; }
三、运行结果
参考:
网络通讯与UI相结合的回调: