我正在使用 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
属性传递给下一个 View Controller :
// 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
。我在代码中留下了一些注释掉的行以显示我尝试过的东西,但我碰壁了。我想我总能创建一本新词典。这是首选的方式吗?
最佳答案
NSJSONSerialization
默认返回不可变对象(immutable对象)。以下是如何从解析器获取可变字典:
- 使用选项
NSJSONReadingMutableContainers
或
- 对结果使用
mutableCopy
关于objective-c - "Mutating method sent to immutable object"尽管对象是 NSMutableDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8299014/