清華大佬耗費(fèi)三個(gè)月吐血整理的幾百G的資源,免費(fèi)分享!....>>>
委托(Delegates)示例
假設(shè)對(duì)象A調(diào)用B來執(zhí)行一項(xiàng)操作,操作一旦完成,對(duì)象A就必須知道對(duì)象B已完成任務(wù)且對(duì)象A將執(zhí)行其他必要操作。
在上面的示例中的關(guān)鍵概念有
- A是B的委托對(duì)象
- B引用一個(gè)A
- A將實(shí)現(xiàn)B的委托方法
- B通過委托方法通知
創(chuàng)建一個(gè)委托(Delegates)對(duì)象
1. 創(chuàng)建一個(gè)單一視圖的應(yīng)用程序
2. 然后選擇文件 File -> New -> File...
3. 然后選擇Objective C單擊下一步
4. 將SampleProtocol的子類命名為NSObject,如下所示
5. 然后選擇創(chuàng)建
6.向SampleProtocol.h文件夾中添加一種協(xié)議,然后更新代碼,如下所示:
#import <Foundation/Foundation.h> // Protocol definition starts here @protocol SampleProtocolDelegate <NSObject> @required - (void) processCompleted; @end // Protocol Definition ends here @interface SampleProtocol : NSObject { // Delegate to respond back id <SampleProtocolDelegate> _delegate; } @property (nonatomic,strong) id delegate; -(void)startSampleProcess; // Instance method @end7. Implement the instance method by updating the SampleProtocol.m file as shown below.
#import "SampleProtocol.h" @implementation SampleProtocol -(void)startSampleProcess{ [NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate selector:@selector(processCompleted) userInfo:nil repeats:NO]; } @end
8. 將標(biāo)簽從對(duì)象庫拖到UIView,從而在ViewController.xib中添加UILabel,如下所示:
9. 創(chuàng)建一個(gè)IBOutlet標(biāo)簽并命名為myLabel,然后按如下所示更新代碼并在ViewController.h里顯示SampleProtocolDelegate
#import <UIKit/UIKit.h> #import "SampleProtocol.h" @interface ViewController : UIViewController<SampleProtocolDelegate> { IBOutlet UILabel *myLabel; } @end
10. 完成授權(quán)方法,為SampleProtocol創(chuàng)建對(duì)象和調(diào)用startSampleProcess方法。如下所示,更新ViewController.m文件
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; SampleProtocol *sampleProtocol = [[SampleProtocol alloc]init]; sampleProtocol.delegate = self; [myLabel setText:@"Processing..."]; [sampleProtocol startSampleProcess]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Sample protocol delegate -(void)processCompleted{ [myLabel setText:@"Process Completed"]; } @end
11. 將看到如下所示的輸出結(jié)果,最初的標(biāo)簽也會(huì)繼續(xù)運(yùn)行,一旦授權(quán)方法被SampleProtocol對(duì)象所調(diào)用,標(biāo)簽運(yùn)行程序的代碼也會(huì)更新。
掃碼二維碼 獲取免費(fèi)視頻學(xué)習(xí)資料
- 本文固定鏈接: http://www.wangchenghua.com/j/ios/1000713/
- 免費(fèi): Python視頻資料獲取