func retrieveMessages() {
var query:PFQuery = PFQuery(className: "Message")
//Call findobjectsinbackground
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
self.messagesArray = [String]()
for messageObject in objects { <<<<<<<<<<<<<<<<< error
let messageText:String? = (messageObject as PFObject)["Text"] as? String
if messageText != nil {
self.messagesArray.append(messageText!)
}
}
self.messageTableView.reloadData()
}
}
从此代码中出现错误:[AnyObject]? does not have a member named 'Generator'
。有没有办法纠正这个问题?
答案 0 :(得分:11)
您的objects
数组被声明为可选:objects:[AnyObject]?
所以你需要在循环之前展开:
for messageObject in objects! {
// do stuff
}
由于objects
可以为零,因此最好这样做:
if let myObjects = objects {
for messageObject in myObjects {
// do stuff
}
}
答案 1 :(得分:2)
那是因为它是一个可选的数组。只需将其包裹在if let
左右,你就可以了。
在操场上:
func retrieveMessages(objects:[AnyObject]?) {
var messagesArray = [String]()
if let objs = objects {
for messageObject in objs {
let messageText:String? = "test"
if messageText != nil {
messagesArray.append(messageText!)
}
}
}
}
在你的情况下,完整的代码是:
func retrieveMessages() {
var query:PFQuery = PFQuery(className: "Message")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
self.messagesArray = [String]()
if let objs = objects {
for messageObject in objs {
let messageText:String? = (messageObject as PFObject)["Text"] as? String
if messageText != nil {
self.messagesArray.append(messageText!)
}
}
}
self.messageTableView.reloadData()
}
}
答案 2 :(得分:1)
由于您的对象Array是[AnyObject] ?,因此在使用它们之前,您需要执行以下步骤。
if let myObjects = objects as? [PFObject] {
//Do the things...
}
答案 3 :(得分:0)
[AnyObject]?它是一个可选的数组。
在使用之前必须打开它。
if let objects = objects
{
for messageObject in objects
{
....
}
}