storing [NSNull null] values in NSUserDefaults, from JSON serialization, causes unwanted exceptions

后端 未结 2 750
暖寄归人
暖寄归人 2020-12-10 07:50

I\'ve got an app where I use a JSON based API. As part of JSON, often values are set to \"null\". This may be common:

{\"data\":[\"one\",\"two\",\"three\"]         


        
相关标签:
2条回答
  • 2020-12-10 08:44

    You can first convert your NSDictionary to NSData, then safely store in NSUserDefaults (since NSNull conforms to NSCoding).

    //archive
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"key"];
    
    //unarchive
    NSData *newData = [[NSUserDefaults standardUserDefaults] objectForKey:@"key"];
    NSDictionary *newDict = [NSKeyedUnarchiver unarchiveObjectWithData:newData];
    

    Edit: Original data object was being referenced instead of newData object.

    0 讨论(0)
  • 2020-12-10 08:52

    I've tried some recursive solutions but they tend to be complicated and don't handle mixed type content well. At the simplest level here is a flat example that works well if you have a predictable, flat response to clean.

    NSMutableDictionary *dictMutable = [dict mutableCopy];
    [dictMutable removeObjectsForKeys:[dict allKeysForObject:[NSNull null]]];
    
    0 讨论(0)
提交回复
热议问题