如何从Swift中的Parse查询结果访问对象的字段? [英] How do you access an object's fields from a Parse query result in Swift?
问题描述
Parse文档提供了使用Swift进行查询的示例,并显示了访问诸如objectId或count之类的内置字段的示例,但是如何访问对象的列之一呢?
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)
}
}
获取错误"AnyObject"无法转换为字符串.
Gets the error "AnyObject" is not convertible to string.
object.objectForKey("name")
还给出了一个错误:找不到接受提供的参数的'objectForKey'的重载"
Also gives an error: "Could not find an overload for 'objectForKey' that accepts the supplied arguments"
现在我还尝试了"as PFObject"或类似的方法,但是它也会导致错误,而且Parse的文档没有显示类似的内容. 类型'[AnyObject]'不能隐式向下转换为'PFObject';您是要使用'as'来强制向下转换吗?"
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?"
然后我应用此修复程序,新的错误是类型'PFObject'不符合协议'SequenceType'
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"]
我得到'AnyObject'无法转换为'String'"
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;
推荐答案
您需要显式转换要检索的属性-
You need to explicitly cast the attribute you are retrieving -
let name = pf["name"] as String
这篇关于如何从Swift中的Parse查询结果访问对象的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!