2016-08-20 59 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中的關閉。 –