iOS – 委託(Delegates)

委託(Delegates)示例

假設物件A呼叫B來執行一項操作,操作一旦完成,物件A就必須知道物件B已完成任務且物件A將執行其他必要操作。

在上面的示例中的關鍵概念有

  • A是B的委託物件
  • B引用一個A
  • A將實現B的委託方法
  • B通過委託方法通知

建立一個委託(Delegates)物件

1. 建立一個單一檢視的應用程式

2. 然後選擇檔案 File -> New -> File...

addNewFile

3. 然後選擇Objective C單擊下一步

4. 將SampleProtocol的子類命名為NSObject,如下所示

setProtocolName

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,如下所示:

delegateLabel

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物件所呼叫,標籤執行程式的程式碼也會更新。

delegateResult