您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 基礎知識 >> iOS 入門介紹

iOS 委託(Delegates)設計模式完整教學

編輯:iOS 入門介紹

委託(Delegates)示例

假設物件 A 請物件 B 執行一項工作,工作完成後,A 需要知道 B 已經辦好,才能接著做後續處理。這就是委託模式的典型情境。

其中的關鍵概念有四點:

  • A 是 B 的委託對象
  • B 持有一個指向 A 的參照
  • A 實作 B 所定義的委託方法
  • B 透過委託方法通知 A

建立一個委託(Delegates)物件

1. 建立一個 Single View Application。

2. 選擇 File → New → File...

3. 選擇 Objective-C,點擊下一步。

4. 將 Subclass of 設為 NSObject,類別命名為 SampleProtocol:

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. 從物件庫拖出一個 UILabel 到 ViewController.xib 的 UIView 上:

9. 建立名為 myLabel 的 IBOutlet,並更新 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. 執行後,標籤會先顯示「Processing...」,待 SampleProtocol 物件呼叫委託方法後,文字隨即更新為「Process Completed」。

實務建議:delegate 屬性應宣告為 weak,避免與對方形成循環參照造成記憶體洩漏。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved