iOS-委託(Delegates)
委託(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@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物件所調用,標籤運行程式的程式碼也會更新。