storing values in NSUserDefaults, from JSON serialization, causes unwanted exceptions
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:
Recently I’ve tried to store a misc NSDictionary hierarchy, converted from a JSON object, in NSUserDefaults. Unfortunately it causes an exception if there is null data, converted in IOS to [NSNull null]. Apparently that can’t be saved in prefs.
I was wondering if anyone has worked around this before? I tried to add some logic to remove all null values from the JSON first, with limited success, but it seems inappropriate to have to modify the data before storing it. Is there a better way to handle this?
- How to convert numbers into text?
- Adding a UIView to a UITableViewCell via cell.contentView
- How to use one IBAction for multiple buttons in Swift?
- Apple Mach -O Linker (Id) Error?
- custom font not displaying on some simulator
- XCode getting “target specifies product type 'com.apple.product-type.bundle.unit-test', but there's no such product type for the 'iphoneos' platform”
2 Solutions Collect From Internet About “storing values in NSUserDefaults, from JSON serialization, causes unwanted exceptions”
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.
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]]];
- Sprite Kit animateWithTextures lags
- Issues after updating to IOS11 and Xcode9!! “com.google.Maps.LabelingBehavior”, “TIC Read Status”
- Get Google contacts using API on iOS
- how to perform Bump Distortion in ios 5.0?
- Continuous integration with Xcode Bots
- Invalid Swift Support / invalid implementation of swift
- Undo core data managed object
- Multiple Custom Rows UITableView?
- Randomizing node movement duration
- Array of UIButtons or method UIButton(named: “\(string)”)
- Cannot load underlying module for 'RealmSwift'
- iOS 8 Touch ID error “User interaction is required.”
- how to get start and end time of today's date in ios?
- how to open the url in safari not in webview
- iOS8 Photos Framework: How to get the name(or filename) of a PHAsset?