iOS開発マニュアル中國語版
/ iOS-委托(Delegates)
iOS-委托(Delegates)
委托(Delegates)示例
假設(shè)對象A調(diào)用B來執(zhí)行一項操作,操作一旦完成,對象A就必須知道對象B已完成任務(wù)且對象A將執(zhí)行其他必要操作。
在上面的示例中的關(guān)鍵概念有
- A是B的委托對象
- B引用一個A
- A將實現(xiàn)B的委托方法
- B通過委托方法通知
創(chuàng)建一個委托(Delegates)對象
1. 創(chuàng)建一個單一視圖的應(yīng)用程序
2. 然后選擇文件 File -> New -> File...
3. 然后選擇Objective C單擊下一步
4. 將SampleProtocol的子類命名為NSObject,如下所示
5. 然后選擇創(chuàng)建
6.向SampleProtocol.h文件夾中添加一種協(xié)議,然后更新代碼,如下所示:
#import <Foundation/Foundation.h>// 協(xié)議定義@protocol SampleProtocolDelegate <NSObject>@required- (void) processCompleted;@end// 協(xié)議定義結(jié)束@interface SampleProtocol : NSObject{ // Delegate to respond back id <SampleProtocolDelegate> _delegate; }@property (nonatomic,strong) id delegate;-(void)startSampleProcess; // Instance method@end
7.修改 SampleProtocol.m 文件代碼,實現(xiàn)實例方法:
#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. 創(chuàng)建一個IBOutlet標簽并命名為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)建對象和調(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é)果,最初的標簽也會繼續(xù)運行,一旦授權(quán)方法被SampleProtocol對象所調(diào)用,標簽運行程序的代碼也會更新。