首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 兩個 ViewController 傳值:臨時變量無法回傳,需用 Delegate 或 Block

     編輯:程式設計綜合問答

問題場景

A 控制器 present B 控制器,B 輸入資料後需回傳給 A。嘗試用共享模型物件 test *t 但 A 收不到更新。

原因

B 中 Example3ViewController *e3v = [[Example3ViewController alloc] init...] **建立了新實例**,並非原本 present A 的實例。A 的 viewWillAppear 不會被再次調用。

正確模式:Delegate 代理

// B 控制器定義協議
@protocol EditorViewControllerDelegate 
- (void)editorDidFinishWithData:(Test *)data;
@end

@interface EditorViewController : UIViewController
@property (weak) id delegate;
@end

// B 完成時
- (IBAction)done {
    Test *t = [[Test alloc] init];
    t.name = self.vtitle.text; ...
    [self.delegate editorDidFinishWithData:t];
    [self dismissViewControllerAnimated:YES completion:nil];
}

// A 實現協議
- (void)editorDidFinishWithData:(Test *)data {
    self.b = data;
    self.labelname.text = data.name; ...
}

// A present B 時設定代理
EditorViewController *editor = [[EditorViewController alloc] init...];
editor.delegate = self;
[self presentViewController:editor animated:YES completion:nil];

替代:Block 回調

// B 定義
@property (copy) void (^completionBlock)(Test *data);

// A 使用
editor.completionBlock = ^(Test *data) {
    self.b = data;
    [self updateUI];
};

核心原則

  • **不要重新初始化** 已經在螢幕上的控制器
  • 資料回傳用 **Delegate / Block / Notification / Closure**
  • 模態呈現後,原控制器 viewWillAppear **不會再次調用**
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved