I'm setting values for properties of my NSManagedObject
, these values are coming from a NSDictionary
properly serialized from a JSON file. My problem is, that, when some value is [NSNull null]
, I can't assign directly to the property:
fight.winnerID = [dict objectForKey:@"winner"];
this throws a NSInvalidArgumentException
"winnerID"; desired type = NSString; given type = NSNull; value = <null>;
我可以很容易地判断[NSNull null]
的值,然后指定nil
:
fight.winnerID = [dict objectForKey:@"winner"] == [NSNull null] ? nil : [dict objectForKey:@"winner"];
But I think this is not elegant and gets messy with lots of properties to set.
此外,在处理NSNumber
处房产时,这会变得更加困难:
fight.round = [NSNumber numberWithUnsignedInteger:[[dict valueForKey:@"round"] unsignedIntegerValue]]
The NSInvalidArgumentException
is now:
[NSNull unsignedIntegerValue]: unrecognized selector sent to instance
In this case I have to treat [dict valueForKey:@"round"]
before making an NSUInteger
value of it. And the one line solution is gone.
我试着制作一个@try@catch块,但是一旦捕捉到第一个值,它就会跳过整个@try块,并且忽略下一个属性.
有没有更好的方法来处理[NSNull null]
个问题,或者让这完全不同但更简单?