Reputation: 10116
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;
Upvotes: 0
Views: 5177
Reputation: 11
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!)
}
}
Upvotes: 1
Reputation: 114856
You need to explicitly cast the attribute you are retrieving -
let name = pf["name"] as String
Upvotes: 7