问题描述
我正在为NSManagedObject
的属性设置值,这些值来自正确地从JSON文件序列化的NSDictionary
.我的问题是,当某些值为[NSNull null]
时,我无法直接分配给该属性:
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"];
这将引发NSInvalidArgumentException
"winnerID"; desired type = NSString; given type = NSNull; value = <null>;
我可以轻松检查[NSNull null]
的值并分配nil
代替:
I could easily check the value for [NSNull null]
and assign nil
instead:
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
属性时,这会变得更加困难:
Also, this gets harder when dealing with NSNumber
properties:
fight.round = [NSNumber numberWithUnsignedInteger:[[dict valueForKey:@"round"] unsignedIntegerValue]]
NSInvalidArgumentException
现在是:
[NSNull unsignedIntegerValue]: unrecognized selector sent to instance
在这种情况下,我必须先对[dict valueForKey:@"round"]
进行处理,然后再对其进行NSUInteger
赋值.一线解决方案不见了.
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块,而下一个属性将被忽略.
I tried making a @try @catch block, but as soon as the first value is caught, it jumps the whole @try block and the next properties are ignored.
是否有更好的方法来处理[NSNull null]
或使它完全不同但更容易?
Is there a better way to handle [NSNull null]
or perhaps make this entirely different but easier?
推荐答案
如果将其包装在宏中,则可能会容易一些:
It might be a little easier if you wrap this in a macro:
#define NULL_TO_NIL(obj) ({ __typeof__ (obj) __obj = (obj); __obj == [NSNull null] ? nil : obj; })
然后您可以编写类似的内容
Then you can write things like
fight.winnerID = NULL_TO_NIL([dict objectForKey:@"winner"]);
或者,您甚至可以尝试将字典填充到托管对象中之前,也可以对其进行预处理,并用nil
替换所有NSNull
.
Alternatively you can pre-process your dictionary and replace all NSNull
s with nil
before even trying to stuff it into your managed object.
这篇关于NSNull处理NSManagedObject属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!