2017-02-16 95 views
1

我正在使用JSONSerializer来访问SQL数据库中的数据。我管理着让数据读入,没有任何问题,并设法获取每个条目并为每个条目创建一个临时对象。我将每个对象添加到一个数组。但是,当我检查此方法外的数组长度时,它返回0,它应该返回5.在整个方法中检查数组的长度时,它返回5.任何建议?Swift - 从JSONElemetns填充数组

代码:

func getJson() { 
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in 
     if error != nil 
     { 
      print("ERROR") 
     } 
     else 
     { 
      if let content = data 
      { 

       do{ 

        let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject 

        for index in 0..<myJson.count { 

        if let entry = myJson[index] as? NSDictionary{ 
         let name = entry["Name"] as! String 
         let longitude = CLLocationDegrees(entry["Longitude"] as! String) 
         let latitude = CLLocationDegrees(entry["Latitude"] as! String) 

         let quiet = Int(entry["Quiet"] as! String) 
         let moderate = Int(entry["Moderate"] as! String) 

         let busy = Int(entry["Busy"] as! String) 
         let coordinate = CLLocationCoordinate2D(latitude: latitude!, longitude: longitude!) 

         let tempPark = CarPark(name: name, latitude: latitude!, longitude: longitude!, quiet: quiet!, moderate: moderate!, busy: busy!, coordinate: coordinate) 

         self.carParks.append(tempPark) 
         print("amount of parks: \(self.carParks.count)") 
         print("name of parks in array: \((self.carParks[index]))") 
         } 

        } 

       } 
       catch 
       { 
        print("Error") 
       } 
      } 
     } 
} 
    print("amount of parks: \(self.carParks.count)") 
    task.resume() 
} 
+1

因为它是asynchrone。检查何时完成日志'print(“公园的数量:\(self.carParks.count)”)'什么时候完成'print(“公园的名称在数组中:\((self.carParks [index])) “) ' – Larme

回答

0

看来你的函数以异步方式工作,这就是为什么当您试图指望它返回0的元素,因为没有元素呢。一旦完成,我会使用完成处理程序来检索数组。

func getJson(completion: @escaping (Array<ObjectType>) -> Void) { 
. 
. 
. 
. 
completion(localCarParks) 
. 
. 
. 
. 
} 

在上面的函数中,定义了处理答案的完成处理程序。在函数内部,一旦完成加载元素,就可以使用localCarPerks数组调用处理程序。

,并调用的getJSON功能,这将是这样的:

self.getJson { (array) in 
    // Here you do what you need with the array 
}