我正在为 NSManagedObject
的属性设置值,这些值来自从 JSON 文件正确序列化的 NSDictionary
。我的问题是,当某个值为 [NSNull null]
时,我无法直接分配给该属性:
fight.winnerID = [dict objectForKey:@"winner"];
这会引发 NSInvalidArgumentException
"winnerID"; desired type = NSString; given type = NSNull; value = <null>;
我可以很容易地检查 [NSNull null]
的值并改为分配 nil
:
fight.winnerID = [dict objectForKey:@"winner"] == [NSNull null] ? nil : [dict objectForKey:@"winner"];
但我认为这并不优雅,并且需要设置很多属性。
此外,在处理 NSNumber
属性时,这会变得更加困难:
fight.round = [NSNumber numberWithUnsignedInteger:[[dict valueForKey:@"round"] unsignedIntegerValue]]
NSInvalidArgumentException
现在是:
[NSNull unsignedIntegerValue]: unrecognized selector sent to instance
在这种情况下,我必须在创建 NSUInteger
值之前处理 [dict valueForKey:@"round"]
。而且单线解决方案已经没有了。
我尝试创建一个@try @catch block ,但是一旦捕获到第一个值,它就会跳过整个@try block 并且忽略下一个属性。
有没有更好的方法来处理 [NSNull null]
或者让这完全不同但更容易?
最佳答案
如果你把它包装在一个宏中可能会更容易一些:
#define NULL_TO_NIL(obj) ({ __typeof__ (obj) __obj = (obj); __obj == [NSNull null] ? nil : obj; })
然后你可以写类似的东西
fight.winnerID = NULL_TO_NIL([dict objectForKey:@"winner"]);
或者,您可以预处理您的字典并将所有 NSNull
替换为 nil
,然后再尝试将其填充到您的托管对象中。
关于objective-c - NSManagedObject 属性值的 NSNull 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9137920/