iOS - 尝试在NSUserDefaults

时间:2016-02-19 02:03:44

标签: ios objective-c nsdictionary nsuserdefaults

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

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

此尝试使用以下消息导致我的应用崩溃:

  

由于未捕获的异常而终止应用   'NSInvalidArgumentException',原因:'尝试插入非属性   列表对象{type =   immutable dict,count = 10,entries => 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:email = {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对象将具有可为空的属性。

2 个答案:

答案 0 :(得分:4)

字典中的某些对象或键具有类,不支持属性列表序列化。有关详细信息,请参阅此答案: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]));
}

答案 1 :(得分:2)

NSNull在JSON中可接受(作为MATCH p=(n:Label{updatetime:'2017/5/1 6:30'})-[r:GO_TO{routeid:'1'}]->() MATCH p1=(n1:Label{updatetime:'2017/5/1 6:30'})-[r1:GO_TO{routeid:'2'}]->() MATCH p2=(n2:Label{updatetime:'2017/5/1 6:30'})-[r2:GO_TO{routeid:'3'}]->() MATCH p3=(n3:Label{updatetime:'2017/5/1 6:35'})-[r3:GO_TO{routeid:'4'}]->() MATCH p4=(n4:Label{updatetime:'2017/5/1 6:45'})-[r4:GO_TO{routeid:'5'}]->() MATCH p5=(n5:Label{updatetime:'2017/5/1 6:45'})-[r5:GO_TO{routeid:'6'}]->() MATCH p6=(n6:Label{updatetime:'2017/5/1 6:50'})-[r6:GO_TO{routeid:'7'}]->() ),但未列在属性列表中。因此,一种解决方案是将字典转换为NSData并保存。 enter image description here