2012-05-11 47 views
0

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

@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' 

回答

2

该数组是可变的,但它是什么... NSDictionary ...不是。你抢的对象从数组中......

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

,然后你尝试变异那个对象......

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

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

+0

Jody是对的,但是:你们都试图修改已经在数组中的字典,也“替换”字典。我把“替换”放在引号中,因为你用自己替换它。您可以使用可变字典并将该调用放到'-replaceObjectAtIndex:withObject:'中,或者您可以继续在数组中使用不可变字典,但会构建一个新的字典并保留替换逻辑。 –

+0

谢谢你们,一个简单的视线,我希望不要再做了! – Xaphann