查詢已同步通過,這意味着query.findObjectsInBackgroundWithBlock
在您返回petitions
時可能無法完成(99%無法完成)。
你可以做你想要直接在功能做你的東西:
var petitions: [PFObject] = [] //class variable
func getPetitions(employeeId: String, employeeBusiness: String) {
var query = PFQuery(className:"Petitions")
query.selectKeys(["petitionDate", "availableFrom", "availableTo"])
query.whereKey("employeeId", equalTo:employeeId)
query.whereKey("employeeBusiness", equalTo:employeeBusiness)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
NSLog("Successfully retrieved \(objects.count) petitions.")
for object in objects {
self.petitions.append(object)
}
// update UI
// or just do whatever you want with the petitions.
}
}
}
}
或者你可以寫一個塊功能:
func getPetitions(employeeId: String, employeeBusiness: String, block:PFArrayResultBlock) {
var query = PFQuery(className:"Petitions")
query.selectKeys(["petitionDate", "availableFrom", "availableTo"])
query.whereKey("employeeId", equalTo:employeeId)
query.whereKey("employeeBusiness", equalTo:employeeBusiness)
query.findObjectsInBackgroundWithBlock(block)
}
}
要叫它:
getPetitions("employeeId", "employeeBusiness", block: {
(objects: [AnyObject]?, error: NSError?) -> Void in
// do whatever you want with your objects..
// update UI
// or just do whatever you want with the petitions.
})
解決這個問題的另一種方法是同步查詢:
func getPetitions(employeeId: String, employeeBusiness: String) -> [PFObject] {
var query = PFQuery(className:"Petitions")
query.selectKeys(["petitionDate", "availableFrom", "availableTo"])
query.whereKey("employeeId", equalTo:employeeId)
query.whereKey("employeeBusiness", equalTo:employeeBusiness)
var objects = query.findObjects()
if let petititons = objects as? [PFObject] {
return petititons
} else {
return [PFObject]() // return an empty pf object array. If you want, return nil.. but the return value must be [PFObject]? if you do this.
}
}
你能給我舉個例子嗎?提前致謝 – Xsan