您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 委派(Delegate)實作教學:讓子頁面把資料回傳給父頁面

編輯:iOS 開發綜合

iOS 的頁面之間要雙向溝通,委派是最經典的方式。場景很常見:A 頁面彈出一個浮層 B,使用者在 B 裡做了某個選擇,A 需要知道並據此動作。

先打了個比方幫助理解:如果沒有設定代理,就像你沒委託我替你辦事,我跑到銀行或公所去,人家當然不理你。委派本質上就是一份授權書——A 說「你(B)完成之後回報給我」,並把自己登記為可回報的對象。

步驟一:在 B 中定義協定

PopViewController.h:

#import <UIKit/UIKit.h>

// 定義回報協定
@protocol PopNextDelegate <NSObject>

- (void)passPopReport:(NSString *)string;

@end


@interface PopViewController : UIViewController

// 宣告一個 delegate 屬性,型別為「實作上述協定的物件」
@property (nonatomic, assign) id <PopNextDelegate> delegate;

- (IBAction)reportAction:(UIButton *)sender;

@end

這裡有個關鍵細節:屬性型別應該寫成 id <PopNextDelegate>,而不是 NSObject <PopNextDelegate> *。前者表示「任何實作了這個協定的物件」,編譯器才會檢查方法是否存在。另外 delegate 應使用 assign / weak,避免循環引用。

步驟二:在 B 中觸發回報

PopViewController.m:

- (IBAction)reportAction:(UIButton *)sender
{
    // 把資料丟回給 delegate
    [self.delegate passPopReport:@"舉報"];
}

步驟三:A 宣告遵守協定

ShowViewController.h:

#import "PopViewController.h"

@interface ShowViewController : UIViewController
    <iCarouselDataSource, iCarouselDelegate,
     UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate,
     PopNextDelegate>
{
    UIView *moreView;
}
@end

在協定清單中加上 PopNextDelegate,編譯器便會要求你實作其中的方法。

步驟四:A 實作回報方法

ShowViewController.m:

// 收到 B 的回報
- (void)passPopReport:(NSString *)string
{
    if ([string isEqualToString:@"舉報"]) {
        ReportViewController *report = [[ReportViewController alloc] init];
        [self.navigationController pushViewController:report animated:YES];
    }
}

步驟五:A 把自己指定為 delegate

這是最後一塊拼圖,也是最常被遺漏的一步——沒有指定,B 的 self.delegate 就是 nil,回報訊息會石沉大海。

- (void)pop:(id)sender
{
    PopViewController *pop = [[PopViewController alloc] init];
    pop.delegate = self;   // 誰實作了 delegate 方法,就指定給誰

    FPPopoverController *basePop =
        [[FPPopoverController alloc] initWithViewController:pop];
    basePop.tint          = FPPopoverLightGrayTint;
    basePop.arrowDirection = FPPopoverArrowDirectionAny;

    [basePop presentPopoverFromView:sender];
}

流程回顧

  1. B 定義協定,宣告 delegate 屬性。
  2. A 宣告遵守協定,實作協定方法。
  3. A 建立 B 的實例時,把自己指派給 b.delegate。
  4. B 在適當時機呼叫 [self.delegate 協定方法],資料回流到 A。

實務上的加分寫法

呼叫 delegate 前先檢查是否實作,可以避免 doesNotRecognizeSelector 崩潰:

if ([self.delegate respondsToSelector:@selector(passPopReport:)]) {
    [self.delegate passPopReport:@"舉報"];
}

若把協定方法標為 @optional,這個檢查就是必要的;標為 @required 時雖有編譯期把關,但 runtime 加上判斷仍是更保險的習慣。

委派的最大好處是低耦合:B 完全不需要知道 A 是什麼類別、也不需要 import A 的標頭檔,只認協定。這讓同一個 B 可以被任何数量的頁面複用。若只需要回傳單一值,block 也是不錯的選擇;但涉及多個回呼、多個狀態時,委派仍是最清晰的解法。

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