簡體   English   中英

在ViewControllers之間共享數據

[英]Sharing data between ViewControllers

我有一個簡單的單視圖iOS 5應用程序,我添加了第二個視圖控制器。 我在導航控制器中嵌入了這些,我在FirstViewController上放了兩個按鈕。 這些按鈕中的每一個都有一個segue的命名標識符,該標識符又在iPhone應用程序的UI中顯示我的SecondViewController。

一切都按預期工作,但是,我想在第二個視圖控制器的標簽上顯示一些簡單的“你點擊按鈕1”。 我已經嘗試將這些數據手動放在我在AppDelegate中聲明的NSMutableString變量中,我可以在第二個視圖控制器中訪問該變量但是我分配給它的值永遠不會顯示在屏幕上。

顯然,創建了一個SecondViewController的新實例,這可能就是我沒有看到它的原因。 我創建了一個名為UILabel的IBOutlet,其名稱為myLabel,用於保存此值,但是我看到沒有變化。

任何幫助將不勝感激。

注意:我很樂意發布代碼,但我認為這不會對我的問題有所幫助。

我在這種情況下的解決方案始終是一個自定義的-init方法。 如,

-initWithButtonPressedString:(NSString*)message;

在第二個視圖控制器中聲明並調用:

self.secondView = [[SecondViewController alloc]initWithButtonPressedString:@"some conditional string"];

然后,所需要的只是第二個視圖控制器中的iVar來處理傳遞的字符串。

要在視圖控制器之間傳遞數據,您應該考慮1.為視圖控制器創建一個自定義init,它傳遞附加信息或2.在第二個視圖控制器上創建屬性,您可以從第一個視圖控制器訪問這些屬性。

您可以為您創建的IBOutlet創建屬性,但是如果從第一個視圖控制器訪問它,則需要確保它在加載視圖之后。

如果沒有看到您當前的代碼,很難給您更多指導

你使用故事板嗎? 無論如何,您是否已將IBOutlet連接到Interface Builder中的變量?

如果您使用Storyboards,您可能會嘗試使用名為- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

即。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"ChooseToDetailsSegue"]) {
        preparedSegue = segue;
        SaleDetailsViewController *saleDetailsVC = [preparedSegue destinationViewController];
        saleDetailsVC.saleDetailsProduct = [elementsArray objectAtIndex:selectedRow];
        saleDetailsVC.cardTransactionDetails = [[cardDetails alloc] init];
        saleDetailsVC.cardTransactionDetails.number = infoCardNumber;
        saleDetailsVC.cardTransactionDetails.month = infoExpiriationM;
        saleDetailsVC.cardTransactionDetails.year = infoExpiriationY;     
    }
}

您只需要初始化新的ViewController(您的目標)並引用它們的變量。

您也可以使用通知。 在FirstViewController的第一個按鈕的IBAction中,您可以添加

NSNotification *messageFromFirstViewController = [NSNotification notificationWithName:@"firstbuttonMessage" object:@"You clicked Button 1"]; [[NSNotificationCenter defaultCenter] postNotification:messageFromFirstViewController];

和你的第二個按鈕的IBAction類似的東西。

在SecondViewController的viewDidLoad中,您可以添加

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(useNotification:) name:@"firstButtonMessage" object:nil];

創建useNotification方法來更改myLabel:

-(void) useNotification:(NSNotification *)notification {
self.myLabel.text = notification.object;}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM