I\'m setting values for properties of my NSManagedObject
, these values are coming from a NSDictionary
properly serialized from a JSON file. My problem
Ok, I've just woke up this morning with a good solution. What about this:
Serialize the JSON using the option to receive Mutable Arrays and Dictionaries:
NSMutableDictionary *rootDict = [NSJSONSerialization JSONObjectWithData:_receivedData options:NSJSONReadingMutableContainers error:&error];
...
Get a set of keys that have [NSNull null]
values from the leafDict:
NSSet *nullSet = [leafDict keysOfEntriesWithOptions:NSEnumerationConcurrent passingTest:^BOOL(id key, id obj, BOOL *stop) {
return [obj isEqual:[NSNull null]] ? YES : NO;
}];
Remove the filtered properties from your Mutable leafDict:
[leafDict removeObjectsForKeys:[nullSet allObjects]];
Now when you call fight.winnerID = [dict objectForKey:@"winner"];
winnerID is automatically going to be (null)
or nil
as opposed to
or [NSNull null]
.
Not relative to this, but I also noticed that it is better to use a NSNumberFormatter
when parsing strings to NSNumber, the way I was doing was getting integerValue
from a nil string, this gives me an undesired NSNumber of 0
, when I actually wanted it to be nil.
Before:
// when [leafDict valueForKey:@"round"] == nil
fight.round = [NSNumber numberWithInteger:[[leafDict valueForKey:@"round"] integerValue]]
// Result: fight.round = 0
After:
__autoreleasing NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
fight.round = [numberFormatter numberFromString:[leafDict valueForKey:@"round"]];
// Result: fight.round = nil