iOS在视图之间传递NSMutableArray并在表视图中加载

时间:2012-08-24 16:07:47

标签: objective-c ios xcode

好吧,我在视图中有NSMutableArray,我想将此数组的值传递给另一个视图。但我不想使用方法[self presentModel view controller ...],因为我只想按下我创建的另一个按钮时显示另一个视图。问题是,当我按下按钮显示数组的值时,数组会丢失其值,返回空,但如果我使用方法[self presentModel view controller ...],它将正确返回值。

CurrentView:

@property and @synthesise AnotherViewController *superAnother


AnotherViewController *anView = [[AnotherViewController alloc]initWithNibName:nil bundle:nil];
superAnother.arrayOfTheAnotherView = [[NSMutableArray alloc]initWithArray:arrayOfTheCurrentView];

另一种观点:

@property and @synthesise NMutableArray *arrayOfTheAnotherView;

NSMultableArray array = [[NSMultableArray alloc]initWithArray:arrayOfTheAnotherView];

使用数组加载表视图:

cell.textLabel.text = [array objectAtIndex:indexPath.row];

3 个答案:

答案 0 :(得分:0)

arrayWithArray不会创建收集对象的其他实例,而是使用相同引用创建另一个数组实例。如果要在弹出窗口或其他任何位置更改数据源对象,则需要使用arrayWithArray:copyItems:复制项目,当然所有包含的对象必须符合NSCopying协议才能复制它们

答案 1 :(得分:0)

在视图控制器之间传递NSMutableArray的另一种方法是:

  • 在界面构建器中,将IBAction添加到第一个视图控制器中的按钮
  • 在两个viewControllers之间添加一个storyboard segue(不是从一个按钮到下一个视图控制器,而是直接在viewControllers之间
  • 为此segue提供唯一标识符
  • 在IBAction中,从第一个视图控制器的按钮添加行

    [self performSegueWithIdentifier:@“myIdentifier”];

  • 然后在第一个视图控制器中,您可以实现委托方法:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    
        if ([[segue identifier] isEqualToString:@"myIdentifier"]) {
    
            SecondViewController *con = [segue destinationViewController];
            con.array = self.array;
        }
    }
    

答案 2 :(得分:0)

此代码存在一些问题:

您定义了superAnother属性,但您没有为其分配任何内容。你的代码应该是这样的:

self.superAnother = [[AnotherViewController alloc] initWithNibName:nil bundle:nil];
self.superAnother.arrayOfTheAnotherView = [[NSMutableArray alloc] initWithArray:arrayOfTheCurrentView];

然后在AnotherViewController.m

cell.textLabel.text = [self.arrayOfTheAnotherView objectAtIndex:indexPath.row];

PS。当然,如果您不使用ARC,请不要忘记释放它们