【问题标题】:iOS - Attempt to insert non-property list object NSDictionary in NSUserDefaultsiOS - 尝试在 NSUserDefaults 中插入非属性列表对象 NSDictionary
【发布时间】:2016-02-19 02:03:43
【问题描述】:

在我的应用程序中,我需要将我的自定义User 对象NSDictionary 保存在我的NSUserDefaults 中。我尝试使用以下代码:

NSDictionary *userObjectDictionary = response[@"user"];
NSLog(@"USER OBJECT:\n%@", userObjectDictionary);
[defaults setObject:userObjectDictionary forKey:@"defaultUserObjectDictionary"];
[defaults synchronize];

此尝试使我的应用程序崩溃并显示以下消息:

由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'尝试插入非属性 列表对象 {type = 不可变字典,计数 = 10,条目 => 0:status_id = 1:{contents = "first_name"} = exampleFirstName 3:id = {value = +2,type = kCFNumberSInt64Type} 4 : {contents = "profile_picture"} = {contents = “http://myDevServer.com/pictures/userName.jpg”} 5: last_name = exampleLastName 7 : 电子邮件 = {contents = "myEmail@gmail.com"} 8 : {contents = "badge_count"} = {value = +0, type = kCFNumberSInt64Type} 9:user_name = userName 10:{contents = "phone_number"} = {contents = "0123456789"} 12:{contents = "status_updated_at"} = } 为关键 defaultUserObjectDictionary'

这是我的User 对象字典在我尝试保存之前的样子:

{
    "badge_count" = 0;
    email = "myEmail@gmail.com";
    "first_name" = exampleFirstName;
    id = 2;
    "last_name" = exampleLastName;
    "phone_number" = 0123456789;
    "profile_picture" = "http://myDevServer.com/pictures/userName.jpg";
    "status_id" = "<null>";
    "status_updated_at" = "<null>";
    "user_name" = userName;
}

是否因为我的User 对象NSDictionary 中有空值而崩溃?我尝试使用带有空值的虚拟数据的常规 NSDictionary 并且它有效。如果这是问题,我该如何绕过这个问题?有时我的User 对象将具有可为空的属性。

【问题讨论】:

    标签: ios objective-c nsdictionary nsuserdefaults


    【解决方案1】:

    字典中的某些对象或键具有类,不支持属性列表序列化。详情请看这个答案:Property list supported ObjC types

    我建议检查对象的关键“profile_picture” - 它可能是 NSURL。

    如果这没有帮助,您可以使用以下代码来识别不兼容的对象:

    for (id key in userObjectDictionary) {
        NSLog(@"key: %@, keyClass: %@, value: %@, valueClass: %@",
              key, NSStringFromClass([key class]),
              userObjectDictionary[key], NSStringFromClass([userObjectDictionary[key] class]));
    }
    

    【讨论】:

    • 我的 profile_picture 在我检查时是一个字符串。 “status_id”和“status_updated_at”虽然属于 NSNull 类。
    • 因此,如果您想将它们存储到NSUserDefaults 中,您只需为“status_id”和“status_updated_at”使用另一种表示形式,例如@(0)NSNumber :)
    • 我将您的答案标记为正确,因为它确认空值导致了问题。我使用NSCoder 来存储我的User 对象的DATA,这不会导致空值出现任何问题。
    【解决方案2】:

    NSNull 在 JSON 中是可接受的(如 "&lt;null&gt;"),但未在属性列表中列出。所以一种解决方案是将字典转换为 NSData 并保存。

    【讨论】:

      猜你喜欢
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      • 2022-01-09
      相关资源
      最近更新 更多