2013-05-20 57 views
3

我試圖通過prepareWithSegue一個數組,但我得到空當我啓動應用程序傳遞一個數組prepareforsegue

這是代碼:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if ([segue.destinationViewController isEqual:@"table"]) { 
     PersonsViewController *person= [[PersonsViewController alloc]init]; 
     [person setAnArray:anArray]; 

     person = segue.destinationViewController; 
    } 
} 

,這是setAnArray方法:

-(void)setAnArray:(NSMutableArray *)anArray 
{ 
    array = [[NSMutableArray alloc]initWithArray:anArray]; 
    if (array != nil) { 
     NSLog(@"array is copied !!"); 
    } 
} 

數據應該從viewController(嵌入UINavigation控制器)傳遞給PersonViewController(這是tableview),沒有任何東西顯示在表上,所以我NSLogged的數組數並發現它爲零,所以我做了一些與此代碼進一步檢查:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
#warning Incomplete method implementation. 
    // Return the number of rows in the section. 
    if (array == nil) { 
     NSLog(@"array is null"); 
    } 
    else 
    { 
     NSLog(@"array count is %lu",(unsigned long)[array count]); 
     return [array count]; 
    } 

和我得到數組爲空消息。

請幫我解決這個

+1

這一行的人= segue.destinationViewController是在寫你分配一些生產線的達人。是segue.destinationViewController PersonsViewController? –

+0

@andrewlattis這絕對是。接得好。是的,你不要在'prepareForSegue'中實例化('alloc' /'init')目標視圖控制器。它已經爲你實例化了。安德魯,如果你張貼這個答案,我會投票! – Rob

回答

3

你爲什麼不只是從故事板分配視圖控制器和傳遞數組作爲視圖控制器的屬性,你將它添加到堆棧之前?即當你在寫你先前已實例化並分配數組人物對象分配segue.destinationViewController到你的人避免使用prepareForSegue

-(void) buttonPressed:(UIButton*) sender 
{ 
    UIStoryBoard *story = [UIStoryboard storyboardWithName:@"Storyboard name"]; 
    YourViewController *vc = [story instantiateViewControllerWithIdentifier:@"identifier"]; 

    vc.array = <you array> 


[self.navigationController pushViewController:vc animated:YES]; 


} 
+0

謝謝你的工作! – faisal60

+0

是的,它可以工作,但你問爲什麼不手動實例化控制器?有很多原因:因爲它擊敗了故事板的許多好處。你不再有你的流量的可視化表示。你不能再使用放鬆節奏。如果您沒有從一個視圖控制器到另一個視圖控制器,則在設計場景時默認情況下不會顯示導航欄。等等。有很多原因不能手動實例化場景。不要誤會我的意思,有時候你必須這樣做,但它會讓我覺得自己是一個可行的解決方法。但通常有更好的方法來做到這一點。 – Rob

+0

據我所知,故事板是監督你的項目的一個不錯的方式,然而,他們在做什麼方面的能力非常有限。此外,例如,如果您的導航欄對您來說非常重要,則可以從幽靈按鈕中繼續。我個人認爲,除了那些對編碼非常陌生的人以外,並沒有看到故事板的好處,也不能將CGRects視覺化 – Rambatino

2

你可能想要做這樣的事情

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    if ([segue.destinationViewController isEqual:@"table"]) { 
     [(PersonsViewController *) segue.destinationViewController setAnArray:anArray]; 
    } 
}