【问题标题】:Initialize NSMutableArray初始化 NSMutableArray
【发布时间】:2026-02-15 11:55:01
【问题描述】:

我是 xcode 3 的新手,我真的需要帮助

我使用 UITableView 和 XML 开发了我的应用程序来显示内容。

我有 3 个 .xib 文件,分别是 rootViewController、SecondViewController 和 mainview。

所以问题是: 当我尝试在 rootViewController 中执行 didSelectrow 并访问 SecondViewController 中的 NSMutableArray *array 并在推送动画之前用 rootViewController 中的新数组值替换 *array 值时。

我的 SecondViewController 上的数组值第一次更改,但是当我按下后退按钮并选择另一行时,我的 SecondViewController 数组保持读取前一个数组而不是更改为新数组。我尝试初始化但没有运气

这是我在 rootViewController UITableview (didSelectRow) 上的代码:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if(2ndController == nil)

2ndController = [[DetailViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]];

    //Declare xml NSMutable array record
    ListRecord *record = [self.entries objectAtIndex:indexPath.row];

    //access SecondViewController NSMutable *record
    2ndController.record = [[[NSMutableArray alloc] init] autorelease];   

        //inserting the value from firstview to secondview before push
    2ndController.record = record;



    //push animation
    [self.navigationController pushViewController:2ndController animated:YES];



}

这是我的第二个视图控制器:

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    switch(indexPath.section)
    {
        case 0:

            [cell setText:record.name];
            break;
        case 1:

            [cell setText:record.Age];
            break;
        case 2:
        [cell setText:record.summary];
            break;
    }

    return cell;
}

希望有人可以帮助我..

提前谢谢.....

【问题讨论】:

  • 那么ListRecord是NSMutableArray的子​​类吗?我很困惑,因为您说您正在设置一个数组,但看起来您实际上是在设置 ListRecord* 类型的属性“记录”

标签: objective-c xcode uitableview nsmutablearray didselectrowatindexpath


【解决方案1】:

几件事,

你会的,

2ndController.record = [[[NSMutableArray alloc] init] autorelease];

并跟进

[cell setText:record.name];

显然,record 属性似乎不是NSMutableArray 的实例,所以我认为数组初始化部分与您所做的一样不正确,并且已经提到,

2ndController.record = record;

但我认为问题在于您保留了 UITableViewController 子类。您是否尝试过重新加载数据?

[self.tableView reloadData];

将其添加到您的DetailViewControllerviewWillAppear 方法中。

【讨论】:

  • 谢谢各位....重新加载数据是我正在寻找的功能..用于初始化..我只是尝试并出错..我知道这是错误的..再次感谢:)
【解决方案2】:

你应该再看看这两行:

2ndController.record = [[[NSMutableArray alloc] init] autorelease];   

//inserting the value from firstview to secondview before push
2ndController.record = record;

第一行对你没有任何用处。它创建并初始化一个新的 NSMutableArray 并将记录属性设置为该新数组。

但是在下一行中,您再次将相同的“记录”属性设置为不同的对象,因此不再引用第一行中的数组。所以你可能还没有创建它。

这完全不是您的问题,但此评论太大而无法评论。 :)

【讨论】: