一、項目結構
二、主要代碼
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; }
三、運行結果