我写了一个类,其中包括从Parse.com获取,更新,添加和删除等方法。
我现在遇到了getFromParse
方法的问题:
class ParseModul {
var returnArray = []
func getFromParse(className:String, whereKey:String, equalTo:String) -> NSArray {
let query : PFQuery = PFQuery(className: className)
query.whereKey(whereKey, equalTo: equalTo)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
var temp = [PFObject]()
for object in objects {
temp.append(object)
}
self.returnArray = temp
print(self.returnArray) // THIS IS THE DATA FROM PARSE
}
} else {
print("Error: \(error!)")
}
}
print(self.returnArray.count) // THIS IS 0
if self.returnArray.count > 0 {
return self.returnArray
} else {
self.returnArray = ["nothing"]
return self.returnArray
}
}
}
我用它:
let parse:ParseModul = ParseModul()
let mydata = parse.getFromParse("UserProfile", whereKey: "username", equalTo: "Phil")
该方法始终返回“无”。
答案 0 :(得分:2)
在获取数据之前,您将返回数组。 在块中获取的数据可能不会在函数中返回。
您可以在自己的区块中获取数据;
func getFromParse(className:String, whereKey:String, equalTo:String, completion:(arr:NSArray) -> Void)
{
let query : PFQuery = PFQuery(className: className)
query.whereKey(whereKey, equalTo: equalTo)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
var temp = [PFObject]()
for object in objects {
temp.append(object)
}
//??self.returnArray = temp
//??print(self.returnArray) // THIS IS THE DATA FROM PARSE
completion(temp);
}
} else {
print("Error: \(error!)")
}
}
}
并像这样使用它;
let parse:ParseModul = ParseModul()
parse.getFromParse("UserProfile", whereKey: "username", equalTo: "Phil", completion: {
(arr:NSArray) -> Void in
self.returnArray = arr
print(self.returnArray) // THIS IS THE DATA FROM PARSE
// DO SOMETHING HERE
})