2013-04-25 30 views
1

我正在使用一個故事板和一個似乎可以正常工作的條件傳輸。但是,當我將字符串傳遞給新的視圖控制器時,當我嘗試使用NSLog將其打印出來時,它在新視圖控制器中顯示爲空。NSString在繼續傳遞後沒有正確傳遞

VC1:

[self performSegueWithIdentifier: @"userDetailsSegue" sender: self]; 


    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
if ([[segue identifier] isEqualToString:@"userDetailsSegue"]) 
{ 
    UIStoryboard *mainStoryboard1 = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; 
    tableView1 * secondView = (tableView1*)[mainStoryboard1 instantiateViewControllerWithIdentifier:@"userDetails"]; 
    //tableView1 * secondView = [[tableView1 alloc] init]; 
    [secondView setNetID:userNameTextField.text]; 
    //NSLog(secondView.netID); 
    NSLog(@"Works"); 
} 
} 

VC2.h:

#import "ViewController.h" 
@interface tableView1 : UITableViewController 
{ 
    NSString *netID; 
} 

@property (nonatomic, retain) IBOutlet NSString *netID; 

@end 

VC2.m:

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
NSLog(@"my netID is: %@", netID); 
NSLog(@"test:");} 

輸出:

2013-04-25 10:23:56.576 HwPlusPlus[14240:c07] Works 
2013-04-25 10:23:56.579 HwPlusPlus[14240:c07] my netID is: (null) 
2013-04-25 10:23:56.580 HwPlusPlus[14240:c07] test: 

我試圖設置netID = [[NString alloc] init];在VC2中,但這也沒有幫助。任何想法我做錯了什麼?它拉起第二視圖控制器只要找到

回答

1

下一次,請用大寫字母爲您VC的第一個字符,並儘量選擇有意義或獨特的名字VCs

VC1:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if([[segue identifier] isEqualToString:@"userDetailsSegue"]) 
    { 
     tableView1 * secondView =segue destinationViewController]; 
     secondView.netID=userNameTextField.text; 
    } 
} 

VC2.h:

#import "ViewController.h" 
@interface tableView1 : UITableViewController 
{ 
    NSString *netID; 
} 

@property (nonatomic, strong)NSString *netID; 

@end 

VC2.m:

@implementation tableView1 
@synthesize netID; 
- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
NSLog(@"my netID is: %@", self.netID); 
} 
0

的問題是這一行:

tableView1 * secondView = (tableView1*)[mainStoryboard1 instantiateViewControllerWithIdentifier:@"userDetails"]; 

現在所作的,不必要的,額外的視圖控制器。不要這樣做!它是錯誤的視圖控制器,它永遠不會出現在界面中;你只是做它,設置它,並毫無意義地扔掉它。 prepareForSegue中的segue已將destinationViewController設置爲即將顯示的視圖控制器。使用:

tableView1 * secondView = (tableView1*)segue.destinationViewController; 
+0

請大家寫下大寫字母!當你命名它時,不要將視圖控制器視爲一個視圖! – matt 2013-04-25 15:40:45

0

你應該試試這個:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
     if ([segue.identifier isEqualToString:@"SegueIdentifier"]) { 
      UIViewController *viewController = segue.destinationViewController; 
      // you can also use custom view controllers but you have to add a cast to that custmo view controller 
      [viewController setNetID:userNameTextField.text]; 
     } 
    } 

還要確保傳遞給UIViewController的值不爲零。