我在我的项目中同时使用了 ObjectMapper ( https://github.com/Hearst-DD/ObjectMapper ) 和 Realm。我的对象都是 RLMObjects;
例如,我有一个包含附件的博客对象:
dynamic var attachments = RLMArray(objectClassName: Attachment.className())
我有一个自定义变压器,它的开头是这样的:
func transformFromJSON(value: AnyObject?) -> RLMArray? {
let attachments = RLMArray(objectClassName: Attachment.className())
if let str = value as? String {
我似乎无法理解如何将它们转换为 RLMArray,我的变压器总是为零。
"attachments" : [
{
"id" : 2,
"file_name" : "img1.jpg",
"url" : "uploads\/img.jpg"
},
{
"id" : 3,
"file_name" : "img1.jpg",
"url" : "uploads\/img.jpg"
},
{
"id" : 4,
"file_name" : "img1.jpg",
"url" : "uploads\/img.jpg"
}
],
我发现很难理解代码,而且我在 xcode 的调试器中也找不到太多帮助。
TL;DR 我的变压器收到零,或者我期待错误的类型如何将值转换为 RLMArray。
更新: 我希望能弄清楚我在苦苦挣扎的是什么。无论如何,为了调试,我更改了我的变压器以包含它:
func transformFromJSON(value: AnyObject?) -> RLMArray? {
let attachments = RLMArray(objectClassName: Attachment.className())
if let val:AnyObject = value {
Debug.log("the val is this \(val)")
Debug.log("the val is this \(val as? String)")
Debug.log("the val is this \(val as? Attachment)")
Debug.log("the val is this \(val as? Array<Attachment>)")
Debug.log("the val is this \(val as? Array<String>)")
Debug.log("the val is this \(val as? Dictionary<String, AnyObject>)")
Debug.log("the val is this \(val as? Dictionary<String, String>)")
let mir = reflect(value)
Debug.log("the mirror is this \(mir)")
}
return attachments
}
更令人困惑的是,第一个 Debug.log(它只是一个 NSLog)。输出以下内容:
the val is this (
{
"file_name" = "img.jpg";
id = 2;
url = "uploads/img.jpg";
},
{
"file_name" = "img2.jpg";
id = 3;
url = "uploads/img2.jpg";
},
{
"file_name" = "img3.jpg";
id = 4;
url = "uploads/img3.jpg";
}
)
据我所知,这既不是 json,也不是数组,也不是字典,导致这些日志行返回:
val 是这个 nil 或者,对于一个数组,val 是这个 Optional([])
更新 它似乎确实是一个元组,所以现在我有了这个:
func transformFromJSON(value: AnyObject?) -> RLMArray? {
let attachments = RLMArray(objectClassName: Attachment.className())
if let val:AnyObject = value {
Debug.log("-- new obj --")
if let arr = value as? Array<(AnyObject)> {
for file_name in arr {
Debug.log("fn: \(file_name)")
}
}
这允许我遍历不同的附件,但现在我仍然必须找出内部对象是什么。
更新 使用“AnyObject”获取元组数组后,它的值似乎是一个 __NSCFDictionary,我可以使用 objectForKey 获取值