2016-08-20 60 views
-1
Parse Server: 2.2.17 (self hosted) 
Parse-SDK-iOS-OSX: 1.14.2 
ParseUI-iOS Version: 1.2.0 
Xcode 7.3.1, Swift 

我是iOS编程新手(20周),并构建一个应用程序以获得乐趣和学习。解析服务器// findObjectsInBackgroundWithBlock //阵列

我有一个解析函数findObjectsInBackgroundWithBlockArray有问题。完成我的功能后,会给我一个初始值的数组。在函数内部我可以看到添加到数组的值。

class UserOverview { 

    var strings: [String] = ["1", "2", "3"] 

    init() { 
     userKcal() 
    } 

    func userKcal() -> [String] { 
     let query = PFQuery(className: "StringClassInParse") 
     query.whereKey("userPointer", equalTo: PFUser.currentUser()!) 
     query.findObjectsInBackgroundWithBlock { (objects, error) in 
      if let returnedObjects = objects { 
       for object in returnedObjects { 
        let kcal = object["kcal"] as? String 
        self.strings.append(kcal!) 
       } 
      } 
      print(self.strings) // output is ["1", "2", "3", "4", "5", "6"] 
     } 
     print(self.strings) // output is ["1", "2", "3"] 
     return strings 
    } 
} 

任何想法? +对不起,这个初学者的问题。

回答

0

您需要使用closures与功能,因为你正在blockblock将在async的方式工作,所以你需要closure声明你的函数,然后返回String阵列与closure

func userKcal(completion: ([String]) ->()) { 
    let query = PFQuery(className: "StringClassInParse") 
    query.whereKey("userPointer", equalTo: PFUser.currentUser()!) 
    query.findObjectsInBackgroundWithBlock { (objects, error) in 
     if let returnedObjects = objects { 
      for object in returnedObjects { 
       let kcal = object["kcal"] as? String 
       self.strings.append(kcal!) 
      } 
     } 
     completion(self.strings) 
    } 
} 

现在调用这个函数像这样

self.userKcal { (strings) ->() in 
    print(strings) 
} 
+0

我不明白的代码(musst分析和学习),但它的工作就像一个风情万种。非常感谢。 –

+0

如果您想了解更多关于此搜索的信息,例如swift中的关闭。 –