您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 頁面傳值實戰:兩個控制器之間的資料雙向傳遞

編輯:iOS 相關教學

控制器之間傳值是 iOS 面試與日常工作裡的必備技能。本文以「控制器 A」與「控制器 B」為例,把順傳與逆傳兩個方向一次講透,並附上一個可直接運行的完整範例。

先釐清兩個名詞

  • 順傳(A → B):資料由 A 傳向 B。做法是建立目標控制器物件,再把資料賦值給它的屬性。
  • 逆傳(B → A):資料由 B 傳回 A。標準做法是 delegate——A 擔任 B 的代理,A 負責監聽、B 負責通知。

下面用一個雙向傳值的 demo 把兩種手法串起來:A 的輸入框打字後跳到 B,B 會顯示這段文字;在 B 修改後返回,A 的下方輸入框會同步更新。

FirstViewController.h

#import <UIKit/UIKit.h>

@interface FirstViewController : UIViewController

@end

FirstViewController.m

#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController () <SecondViewControllerDelegate>

/** 用於寫入資料,最後傳給第二個介面 */
@property (weak, nonatomic) IBOutlet UITextField *first2Second;

/** 用於顯示第二個介面回傳的資料 */
@property (weak, nonatomic) IBOutlet UITextField *displayWithSecond;

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - Navigation

// 點擊傳遞按鈕時會自動呼叫此方法
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    SecondViewController *vc = (SecondViewController *)segue.destinationViewController;

    // 順傳:把本頁的資料交給目標控制器
    if (self.first2Second.text.length > 0) {
        vc.name = self.first2Second.text;
    }

    // 同時把自己設為 B 的代理,準備接收逆傳資料
    vc.delegate = self;
}

#pragma mark - 實作 SecondViewControllerDelegate

- (void)secondViewControllerDidDit:(SecondViewController *)viewController
                           andName:(NSString *)name {
    // 逆傳:接收第二個介面回傳的資料並顯示
    self.displayWithSecond.text = name;
}

@end

SecondViewController.h

這裡是逆傳的核心:先用 @class 前向宣告避開循環引用,再定義協定。

#import <UIKit/UIKit.h>

@class SecondViewController;

@protocol SecondViewControllerDelegate <NSObject>

/** SecondViewControllerDelegate 協定中的方法 */
- (void)secondViewControllerDidDit:(SecondViewController *)viewController
                            andName:(NSString *)name;

@end

@interface SecondViewController : UIViewController

@property (nonatomic, strong) NSString *name;
@property (nonatomic, weak) id<SecondViewControllerDelegate> delegate;

@end

SecondViewController.m

#import "SecondViewController.h"

@interface SecondViewController ()

/** 用於寫入資料,最後回傳給第一個介面 */
@property (weak, nonatomic) IBOutlet UITextField *second2First;

/** 用於顯示第一個介面傳來的資料 */
@property (weak, nonatomic) IBOutlet UITextField *displayWithFirst;

/** 點擊此按鈕會讓本控制器出棧,介面返回上一頁 */
- (IBAction)second2First:(UIButton *)sender;

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 顯示第一個介面傳過來的資料
    self.displayWithFirst.text = self.name;
}

- (IBAction)second2First:(UIButton *)sender {
    if (self.second2First.text.length > 0) {
        // 只有當對方實作了該協議方法時才回呼,避免 crash
        if ([self.delegate respondsToSelector:@selector(secondViewControllerDidDit:andName:)]) {
            [self.delegate secondViewControllerDidDit:self andName:self.second2First.text];
        }
    }

    [self.navigationController popViewControllerAnimated:YES];
}

@end

幾個實務上的提醒

第一,prepareForSegue:sender: 是 storyboard 場景下做順傳最省事的位置,跳轉發生前就會被呼叫,此時同時完成「賦值」與「設定 delegate」剛剛好。

第二,逆傳前務必用 respondsToSelector: 做保護。若 delegate 為 nil 或未實作該方法,直接呼叫會造成崩潰。

第三,delegate 屬性一定要宣告為 weak,否則 A 持有 B、B 又持有 A,會形成循環引用導致記憶體洩漏。

如果頁面層級較深、需要跨越多層回傳,則可以改用通知(NSNotificationCenter)或 block 回呼,它們在解耦上比 delegate 更進一步,代價是資料流向變得較不直觀。可依專案規模自行取捨。

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