我正在开发一个简单的 iOS 应用程序。这是一个简单的测验应用程序。我正在使用 Parse 来存储我的问题、答案等。我已经阅读了所有文档,但无法找到为什么这段检索对象的代码不起作用。
var query = PFQuery(className: "Test_Questions")
query.getObjectInBackgroundWithId("cJzv2JdMej", block: {
(questionObject: PFObject?, error: NSError?) -> Void in
let thisQuestion = questionObject["question"] as! String
//Error here: AnyObject is not convertible to String
})
非常感谢您的帮助!
控制台输出:
可选(什么语句必须出现在 else 语句之前?)
最佳答案
你应该试试这个:
var query = PFQuery(className: "Test_Questions")
query.getObjectInBackgroundWithId("cJzv2JdMej", block: {
(questionObject: PFObject?, error: NSError?) -> Void in
if error == nil {
println(questionObject)
//if there's info in the console you know the object was retrieved
let thisQuestion = questionObject["question"] as? String
} else {
println("Error occurred retrieving object")
}
})
如果这不起作用,您也可以尝试 let thisQuestion = questionObject.valueForKey("question")
。还要确保 Parse 实际上返回了一个对象,方法是在检索到对象后添加诸如 println(questionObject)
之类的打印语句,这样您就知道 Parse 正在返回一个对象。
关于ios - 使用 Swift 从 Parse 中检索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31655531/