简体   繁体   English

使用Swift从Parse检索对象

[英]Retrieve object from Parse with Swift

I'm developing a simple iOS application. 我正在开发一个简单的iOS应用程序。 It's a simple quiz app. 这是一个简单的测验应用程序。 I'm using Parse to store my questions, answers etc. I've read all the documentation and cannot find why this code to retrieve an object is not working. 我正在使用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

})

Your help would be much appreciated! 您的帮助将不胜感激!

Console Output: 控制台输出:

Optional(What statement must come before an else statement?) 可选(else语句之前必须有什么语句?)

You should try this instead: 您应该尝试以下方法:

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")
    }
})

If that doesn't work you can also try let thisQuestion = questionObject.valueForKey("question") . 如果那不起作用,您也可以尝试let thisQuestion = questionObject.valueForKey("question") Also make sure that Parse is actually returning an object by adding a print statement such as println(questionObject) after it has been retrieved so that you know Parse is returning an object. 还可以通过在检索到语句后添加诸如println(questionObject)类的打印语句来确保Parse实际上正在返回对象,以使您知道Parse正在返回对象。

Got it! 得到它了!

var query = PFQuery(className: "Test_Questions")
    query.getObjectInBackgroundWithId("cJzv2JdMej", block: {
        (questionObject: PFObject?, error: NSError?) -> Void in

        let thisQuestion: AnyObject! = questionObject!.valueForKey("question")

        self.question.text = thisQuestion as? String

        })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM