2

我以前也遇到过这样的问题,并没有得到满意的答复。

我有一个带有名为“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。

这是怎么发生的?我了解类捆绑包(或者我认为我还是这样做了),但这显然是一种特定类型,并且它在某些时候失去了它的子类化,从而杀死了整个事情。我只是完全不明白为什么会发生这种情况。

4

2 回答 2

4

我的猜测是您没有正确分配数组(例如,NSMutableArray *arr = [[NSArray alloc] init]或分配NSArrayNSMutableArray变量)。您可以发布初始化数组的代码吗?

于 2010-05-17T14:11:51.457 回答
1

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

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

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

于 2010-05-17T14:14:53.517 回答