假設對象A調用B來執行一項操作,操作一旦完成,對象A就必須知道對象B已完成任務且對象A將執行其他必要操作。
在上面的示例中的關鍵概念有
創建一個委托(Delegates)對象
1. 創建一個單一視圖的應用程序
2. 然後選擇文件 File -> New -> File...
3. 然後選擇Objective C單擊下一步
4. 將SampleProtocol的子類命名為NSObject,如下所示
5. 然後選擇創建
6.向SampleProtocol.h文件夾中添加一種協議,然後更新代碼,如下所示:
#import <Foundation/Foundation.h> // 協議定義 @protocol SampleProtocolDelegate <NSObject> @required - (void) processCompleted; @end // 協議定義結束 @interface SampleProtocol : NSObject { // Delegate to respond back id <SampleProtocolDelegate> _delegate; } @property (nonatomic,strong) id delegate; -(void)startSampleProcess; // Instance method @end
7.修改 SampleProtocol.m 文件代碼,實現實例方法:
#import "SampleProtocol.h" @implementation SampleProtocol -(void)startSampleProcess{ [NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate selector:@selector(processCompleted) userInfo:nil repeats:NO]; } @end
8. 將標簽從對象庫拖到UIView,從而在ViewController.xib中添加UILabel,如下所示:
9. 創建一個IBOutlet標簽並命名為myLabel,然後按如下所示更新代碼並在ViewController.h裡顯示SampleProtocolDelegate
#import <UIKit/UIKit.h> #import "SampleProtocol.h" @interface ViewController : UIViewController<SampleProtocolDelegate> { IBOutlet UILabel *myLabel; } @end
10. 完成授權方法,為SampleProtocol創建對象和調用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. 將看到如下所示的輸出結果,最初的標簽也會繼續運行,一旦授權方法被SampleProtocol對象所調用,標簽運行程序的代碼也會更新。