简体   繁体   中英

How do you access an object's fields from a Parse query result in Swift?

The Parse documentation provides examples of queries using Swift, and they show an example accessing a built-in field like objectId or count, but what about accessing one of the columns of the object?

    var query = PFQuery(className: "MyObject")
    query.findObjectsInBackgroundWithBlock {
            (objects: [AnyObject]!, error: NSError!) -> Void in
            if !(error != nil) {
                for object in objects {
                    println(object["name"])
            }
            else {
                println("%@", error)
            }
    }

Gets the error "AnyObject" is not convertible to string.

object.objectForKey("name")

Also gives an error: "Could not find an overload for 'objectForKey' that accepts the supplied arguments"

Now I also tried "as PFObject" or something similar, but it also results in errors plus Parse's documentation doesn't show anything like that. "Type '[AnyObject]' cannot be implicitly downcast to 'PFObject'; did you mean to use 'as' to force downcast?"

Then I apply the fix, the new error is "Type 'PFObject' does not conform to protocol 'SequenceType'

Tried also downcasting inside the loop with

let pf = object as PFObject

but that doesn't seem to help because when I do

let name = pf["name"]

I get "'AnyObject' is not convertible to 'String'"

Thanks for your help. I'm sure I'm missing something obvious, since I haven't found anything yet;

您需要显式转换您正在检索的属性 -

let name = pf["name"] as String

This worked for me:

    var query = PFQuery(className: "People")
    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!) -> Void in

        if error == nil {

            // query successful - display number of rows found
            println("Successfully retrieved \(objects.count) people")

            // print name & hair color of each person found
            for object in objects {

                let name = object["name"] as NSString
                let color = object["hairColor"] as NSString

                println("\(name) has \(color) hair")

            }
        } else {

            // Log details of the failure
            NSLog("Error: %@ %@", error, error.userInfo!)
        }
    }

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