委託(Delegates)示例
假設對象A調用B來執行一項操作,操作一旦完成,對象A就必須知道對象B已完成任務且對象A將執行其他必要操作。
在上面的示例中的關鍵概念有
- A是B的委託對象
- B引用一個A
- A將實現B的委託方法
- B通過委託方法通知
創建一個委託(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
@end7.修改 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對象所調用,標籤運行程式的代碼也會更新。
