2012-05-11 68 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