传递数组使用prepareforsegue方法

3
我试图通过prepareWithSegue传递一个数组,但是当我启动应用程序时,它返回null。
这是代码:
-(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 !!");
    }
}

数据应该从嵌入有UINavigation Controller的viewController传递到PersonViewController(表视图),但在表格中没有显示任何内容,所以我记录了数组计数并发现它为零,所以我使用以下代码进行了进一步检查:
- (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
这行代码 person = segue.destinationViewController 正在覆盖你在几行之前分配的 person。segue.destinationViewController 是一个 PersonsViewController 吗? - andrew lattis
@andrewlattis,没错,你说得对。很好的发现。是的,在prepareForSegue中不需要实例化(alloc/init)目标视图控制器。它已经为您实例化了。Andrew,如果您将其发布为答案,我会点赞的! - Rob
2个回答

3
为什么不直接从故事板中分配视图控制器,并在将其添加到堆栈之前将数组作为该视图控制器的属性传递进去?也就是避免使用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];


}

是的,它可以工作,但你为什么不手动实例化控制器呢?有很多原因:因为这样会削弱Storyboard的许多优点。你将不再拥有流程的视觉表示。你将无法再使用"unwind segues"。如果您没有从一个视图控制器到另一个视图控制器的推送segue,则在设计场景时导航栏将不会自动显示出来。等等。有很多原因不要手动实例化场景。别误解我,有时你必须以这种方式做,但我认为这是一种笨拙的解决方法。但通常有更好的方法来完成这项任务。 - Rob
我知道Storyboard是一个很好的监督项目的方式,但它们在功能上有一定的限制。此外,如果您的导航栏非常重要,您可以从幽灵按钮进行Segue。个人而言,除了对于那些刚开始学习编码且无法在脑海中想象CGRects的人来说,我并不认为Storyboard有什么好处。 - Rambatino

2
当您将segue.destinationViewController分配给person时,您正在覆盖先前实例化并将数组分配给它的person对象。
您可能想要这样做:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.destinationViewController isEqual:@"table"]) {
        [(PersonsViewController *) segue.destinationViewController setAnArray:anArray];
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接