objective-c - "Mutating method sent to immutable object"尽管对象是 NSMutableDictionary

标签 objective-c ios cocoa-touch nsdictionary nsmutabledictionary

我正在使用 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/

相关文章:

ios - 每天在设定的时间用 swift 重复本地通知

iphone - iPhone 应用程序内的多种语言选择选项

objective-c - 如何使用swift检测tvOS越狱

ios - 为什么UIViewController子类的xib中是UIView而不是UIViewController?

ios - Swift 框架可以引用另一个 Swift 框架的类扩展吗?

iphone - 在以编程方式移动的 ScrollView 中检测到 "end decelerating"

ios - iPhone-播放电影后,播放音频效果不佳

ios - 核心数据 - 获取与数组中的值之一匹配的属性

ios - 使用更新的框架解析在 iOS 9 构建中损坏的推送通知

iPhone SDK - UIWebView 上面有一个灰色框