0

I'm developing a simple iOS application. 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.

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?)

1
  • try printing questionObject and error (println("Object: (questionObject) - Error: (error)")) Commented Jul 27, 2015 at 14:30

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

16 Comments

You should add the else statement in case error != nil printing the error returned
You're right I added the check for error they didn't originally have but I was being lazy by not adding the else check, thanks.
1 more thing, it should be: println("Error occurred retrieving object, error: (error)")
Well that's just symantics and debugging preferences at that point, but yes that would be helpful.
Ok so now I have a UI Label like so: @IBOutlet weak var question: UILabel! how do I append this to output the question using that? I still get the AnyObject String error.
|
0

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

        })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.