【发布时间】:2011-11-28 16:32:14
【问题描述】:
我正在使用 NSMutableDictionary 并遇到此错误:
'NSInternalInconsistencyException', reason: '-[__NSCFDictionary removeObjectForKey:]: mutating method sent to immutable object'
代码如下:
// Turn the JSON strings/data into objects
NSError *error;
NSMutableDictionary *invoiceDictFromReq = [[NSMutableDictionary alloc] init];
// invoiceDictFromReq = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
invoiceDictFromReq = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error]];
NSLog(@"invoiceDictFromReq count: %i, key: %@, value: %@", [invoiceDictFromReq count], [invoiceDictFromReq allKeys], [invoiceDictFromReq allValues]);
// Get values and keys from JSON response
self.invoiceDict = [invoiceDictFromReq objectForKey:@"invoice"];
NSNumber *invoiceAmount = [self.invoiceDict objectForKey:@"amount"];
NSNumber *invoiceId = [self.invoiceDict objectForKey:@"id"];
NSNumber *invoiceNumber = [self.invoiceDict objectForKey:@"number"];
NSNumber *checkoutStarted = [self.invoiceDict objectForKey:@"checkoutStarted"];
NSNumber *checkoutCompleted = [self.invoiceDict objectForKey:@"checkoutCompleted"];
NSLog(@"amount: %@, id: %@, number: %@, started: %@, completed: %@", invoiceAmount, invoiceId, invoiceNumber, checkoutStarted, checkoutCompleted);
所有控制台日志都表明数据正常。这就是事情开始崩溃的地方。
我将invoiceDict 属性传递给下一个视图控制器:
// Pass the invoice to checkoutViewController
[checkoutViewController setInvoiceDict:self.invoiceDict];
在 CheckoutViewController.m 中:
// Change invoice checkoutCompleted to true
// [self.invoiceDict removeObjectForKey:@"checkoutCompleted"];
[self.invoiceDict setObject:[NSNumber numberWithBool:YES] forKey:@"checkoutCompleted"];
错误位于[self.invoiceDict setObject...]。我确保我使用的所有字典都是NSMutableDictionary。我在代码中留下了一些注释掉的行来显示我尝试过的东西,但我碰了壁。我想我总是可以创建一个新字典。这是首选的方法吗?
【问题讨论】:
标签: objective-c ios cocoa-touch nsdictionary nsmutabledictionary