[英]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? Parse 文档提供了使用 Swift 进行查询的示例,它们展示了一个访问内置字段(如 objectId 或 count)的示例,但是如何访问对象的列之一呢?
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.获取错误“AnyObject”不可转换为字符串。
object.objectForKey("name")
Also gives an error: "Could not find an overload for 'objectForKey' that accepts the supplied arguments"还给出了一个错误:“找不到接受所提供参数的‘objectForKey’的重载”
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.现在我也尝试了“作为 PFObject”或类似的东西,但它也会导致错误,而且 Parse 的文档没有显示类似的东西。 "Type '[AnyObject]' cannot be implicitly downcast to 'PFObject'; did you mean to use 'as' to force downcast?"
“类型 '[AnyObject]' 不能隐式向下转换为 'PFObject';您的意思是使用 'as' 强制向下转换吗?”
Then I apply the fix, the new error is "Type 'PFObject' does not conform to protocol 'SequenceType'然后我应用了修复,新的错误是“类型‘PFObject’不符合协议‘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'"我得到“'AnyObject' 不能转换为'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!)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.