2012-04-09 35 views
0

在一個課程中,列出了包含所有朋友及其ID的列表。現在,當您單擊UITableView中的項目時,會出現「聊天」([self performSegueWithIdentifier: @"showChat" sender: self];)。但是在ChatViewController類中,我需要從FirstViewController訪問變量userID。我嘗試了我在互聯網上找到的所有內容,但它總是給出錯誤或變量爲空。 在FirstViewController是一個NSString userid,所以我怎麼能在ChatViewController.m中訪問這個?我試圖使變量@public,我試圖@property與readwrite等,但它不起作用。 例如對於這一點:將NSString授予其他課程

FirstViewController *fvc = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil]; 
userID = fvc.userID; 

只是給出了一個空字符串..

感謝您的幫助!

回答

4

您需要有prepareForSegue:方法來傳遞變量。

實現如下方法:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    // Make sure your segue name in storyboard is the same as this line 
    if ([[segue identifier] isEqualToString:@"showChat"]) 
    { 
     // Get reference to the destination view controller 
     ChatViewController *cvc = [segue destinationViewController]; 

     // Set the object to the view controller here, like... 
     cvc.userID = self.userID; 
    } 
} 

您可以傳遞值通過SEGUE找到tutorial here

更新

類似的問題已經被問here

4

你寫在ChatViewController正確的驗證碼。你在哪裏做一個FirstViewController的新實例。 這就是問題,新實例的userID始終爲空。

FirstViewController *fvc = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil]; 
userID = fvc.userID; 

ü需要有烏爾FirstViewController的舊實例或當ü去FirstViewController到ChatViewController u必須將該值傳遞給用戶id = fvc.userID;

ChatViewController *cvc = [ChatViewController new]; 
    cvc.userID = self.userID; 
[self.navigationController pushViewController:cvc animated:YES]; 

請記住,您已設置屬性並在ChatViewController中合成userID。

相關問題