【问题标题】:Passing an array with prepareforsegue使用 prepareforsegue 传递数组
【发布时间】:2013-05-20 18:19:09
【问题描述】:

我试图通过 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 !!");
    }
}

数据应该从 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];
    } 

我得到 array is null 消息。

请帮我解决这个问题

【问题讨论】:

  • 这一行 person = segue.destinationViewController 写完了你分配了几行的人。 segue.destinationViewController 是 PersonsViewController 吗?
  • @andrewlattis 绝对是这样。接得好。是的,您不会在prepareForSegue 中实例化 (alloc/init) 目标视图控制器。它已经为您实例化了。安德鲁,如果你把它作为答案发布,我会投赞成票!

标签: iphone ios nsarray


【解决方案1】:

为什么不直接从情节提要分配视图控制器并将数组作为该视图控制器的属性传入,然后再将其添加到堆栈中?即避免使用 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];


}

【讨论】:

  • 是的,它可以工作,但你问为什么不手动实例化控制器?有很多原因:因为它打败了故事板的许多好处。您不再有流程的可视化表示。你不能再使用 unwind segues 了。如果您没有从一个视图控制器到另一个视图控制器的 push segue,则在设计场景时默认不会显示导航栏。等等。有很多理由不手动实例化场景。不要误会我的意思,有时你必须这样做,但我觉得这是一个笨拙的解决方法。但通常有更好的方法来做到这一点。
  • 我知道情节提要是监督项目的一种很好的方式,但是,它们的功能非常有限。此外,例如,如果您的导航栏对您来说真的很重要,您可以从幽灵按钮中分离出来。我个人没有看到故事板的好处,除了那些对编码非常陌生且无法在脑海中可视化 CGRects 的人
【解决方案2】:

当您将 segue.destinationViewController 分配给 person 时,您将覆盖您之前实例化并将数组分配给的 person 对象。

你可能想做这样的事情

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

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 1970-01-01
    • 2012-02-06
    • 2015-09-18
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多