ios回呼函數的標準實現:protocol+delegate

來源:互聯網
上載者:User

一、項目結構

  

二、主要代碼

  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相結合的回調:

  http://blog.csdn.net/z251257144/article/details/7175516

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.