0

我有一个全局 NSMutableArray,我需要用值更新它。NSMutableArray 在 .h 中定义如下;

@property (strong, nonatomic) NSMutableArray *myDetails;

在 viewDidLoad 中像这样预填充;

    NSDictionary *row1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"1", @"rowNumber", @"125", @"yards", nil];
    NSDictionary *row2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"2", @"rowNumber", @"325", @"yards", nil];
    NSDictionary *row3 = [[NSDictionary alloc] initWithObjectsAndKeys:@"3", @"rowNumber", @"525", @"yards", nil];
self.myDetails = [[NSMutableArray alloc] initWithObjects:row1, row2, row3, nil];

然后,当用户更改文本字段时,此代码将运行此代码;

-(void)textFieldDidEndEditing:(UITextField *)textField{
    NSObject *rowData = [self.myDetails objectAtIndex:selectedRow];

    NSString *yards = textField.text;

    [rowData setValue:yards forKey:@"yards"];

    [self.myDetails replaceObjectAtIndex:selectedRow withObject:rowData];
}

单步执行代码时 [rowData setValue:yards forKey:@"yards"]; 它返回此错误;

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
4

1 回答 1

2

该数组是可变的,但其中的内容... NSDictionary... 不是。你从数组中抓取一个对象......

NSObject *rowData = [self.myDetails objectAtIndex:selectedRow];

然后你尝试改变那个对象......

[rowData setValue:yards forKey:@"yards"];

数组中的对象就是你要改变的东西……它是 NSDictionary,不可变的,你不能改变它。如果你希望字典是可变的,你必须使用 NSMutableDictionary

于 2012-05-11T02:46:55.000 回答