简体   繁体   中英

Parse and Swift 1.2 issue

This code worked fine in Swift 1.1 ... just trying to figure out what's changed in 1.2 to make it incompatible:

@IBAction func load_click(sender: AnyObject) {

    var query = PFQuery(className: "myClass")
    query.getObjectInBackgroundWithId("MPSVivtvJR", block: { (object:PFObject!, error: NSError) -> Void in

        let theName = object["name"] as String
        let theAge = object["age"] as Int?

        println(theName)
        println(theAge)

    })
}

It gives me the error: Cannot invoke 'GetObjectInBackgroundWithId' with an argument list of type '(String, block: (PFObject!, NSError) -> Void)

Any ideas? Thanks!

Now with Swift 1.2 you are supposed to be more careful with unwrapping optionals. So inside the closure where you have PFObject and NSError , either remove the exclamation marks or add a question mark to make it optional.

Then, unwrap your object more safely. Try as follows:

// You can create this in a separate file where you save your models

struct myUser {
    let name: String?
    let age: Int?
}

// Now this in the view controller

@IBAction func load_click(sender: AnyObject) {
    var query = PFQuery(className: "myClass")
    query.getObjectInBackgroundWithId("MPSVivtvJR", block: {
        (object:PFObject!, error: NSError?) -> Void in

        if let thisName = object["name"] as? String{
            if let thisAge = object["age"] as? Int{
                let user = myUser(name: thisName, age: thisAge)
                println(user)
            }
        }

    })
}

I struggled with this a lot, but the code below works for me.

    var query = PFQuery(className: "class")
    query.whereKey("user", equalTo: PFUser.currentUser()!)
    query.orderByDescending("createdAt")
    var object = query.getFirstObject()

    if let pfObject = object {
        data.variable = (pfObject["variable"] as? Float)!
    }

The accepted answer doesn't work for me. Here's what did work:

var query = PFQuery(className: "score")
query.getObjectInBackgroundWithId("j5xBfJ9YXu", block: {
    (obj, error)in
    if let score = obj! as? PFObject {
        println(score.objectForKey("name"))
    } else {
        println(error)
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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