NSMutableArray无法添加到

时间:2010-05-17 14:08:46

标签: iphone objective-c mutability

我以前遇到过这种问题,并没有得到满意的答案。

我有一个viewcontroller,它有一个名为“counties”的属性,它是一个NSMutableArray。我将在导航屏幕下钻取到关于选择地理搜索的县的视图。因此,搜索页面会向下钻取到“选择县”页面。

当我在导航堆栈上推送第二个控制器时,我将NSMutableArray *counties传递给第二个控制器。我实际设置了第二个控制器的“selectedCounties”属性(也是一个NSMutableArray),带有指向我的第一个控制器的“县”的指针,如下所示。

当我去addObject时,我明白了:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '*** -[NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'

这是我的代码:

在SearchViewController.h中

@interface SearchViewController : UIViewController 
{
    ....
    NSMutableArray *counties;
}

....
@property (nonatomic, retain) NSMutableArray *counties;
SearchViewController.m中的

- (void)getLocationsView
{
    [keywordField resignFirstResponder];
    SearchLocationsViewController *locationsController = 
            [[SearchLocationsViewController alloc] initWithNibName:@"SearchLocationsView" bundle:nil];
    [self.navigationController pushViewController:locationsController animated:YES];
    [locationsController setSelectedCounties:self.counties];
    [locationsController release];
}
SearchLocationsViewController.h中的

@interface EventsSearchLocationsViewController : UIViewController 
    <UITableViewDelegate, UITableViewDataSource>
{
    ...
    NSMutableArray *selectedCounties;

}

...
@property (nonatomic, retain) NSMutableArray *selectedCounties;
在SearchLocationsViewController.m中的

(这里的一点是,我们在所选县的列表中切换活动或不活动的表的每个元素):

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([self.selectedCounties containsObject:[self.counties objectAtIndex:indexPath.row]]) {
        //we're deselcting!
        [self.selectedCounties removeObject:[self.counties objectAtIndex:indexPath.row]];
        cell.accessoryView = [[UIImageView alloc]
                              initWithImage:[UIImage imageNamed:@"red_check_inactive.png"]];
    }
    else {
        [self.selectedCounties addObject:[self.counties objectAtIndex:indexPath.row]];
        cell.accessoryView = [[UIImageView alloc]
                              initWithImage:[UIImage imageNamed:@"red_check_active.png"]];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

我们死在[self.selectedCounties addObject....那里。

现在,当我自己NSLog [self.selectedCounties class]时,它告诉我它是一个NSCFArray。

这是怎么发生的?我理解类捆绑(或者我认为我仍然这样做),但这显然是一种特定的类型,它在某种程度上以一种杀死整个事物的方式失去了它的子类。我完全不明白为什么会这样。

2 个答案:

答案 0 :(得分:4)

我的猜测是你没有正确分配数组(例如,NSMutableArray *arr = [[NSArray alloc] init],或者正在为NSArray变量分配NSMutableArray。你能在初始化的地方发布代码吗?数组?

答案 1 :(得分:1)

您在哪里初始化您设置为县的对象?也许你犯了一个错误:

NSMutableArray *counties = [[NSMutableArray alloc] init];

在这种情况下,不会弹出编译错误,但您无法对创建的数组进行更改!