objective-c - NSManagedObject 属性值的 NSNull 处理

标签 objective-c json parsing nsmanagedobject nsnull

我正在为 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/

相关文章:

c++ - 为什么 glScaled(1, 1, 5) 会改变 glVertex3d(1, 1, 0) 的光照?

objective-c - ARC 下的 stringWithFormat 与 initWithFormat

javascript - JSON 编码 MySQL 数组并在 Google map 上显示

c# - 防止 EntityFramework 返回 json 字符串的转义引号

json - 如何在 JSON 中转义双引号

python - 限制传入消息以避免重复的最佳方法

iphone - 系统库中的内存泄漏

objective-c - 在 NSTextView 中获取 NSTextAttachmentCell 的框架

c - 如何解析 MDNS 响应?

string - 分割路径并仅取出最后一部分(文件名)Powershell