2013-05-20 58 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]; 
    } 
}