我正在尝试根据某些参数恢复所有动物对象。首先,我需要从解析中检索它们的位置以及名称,但由于我要导入多个并使用地理编码器,所以我使用的是字符串,而不是数组。因此,我不是将导入的信息附加到数组中,而是改变一个变量。我认为会发生的情况是,查询将遍历第一个对象,然后运行retrieveLocation方法,然后继续处理从解析导入的下一个对象,但它会导入所有内容,然后运行该方法,所以最后我只得到1个对象应该进口多少。
let query = PFQuery(className: "Animals")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) in
if(error == nil){
for object in objects!{
if let addressobj = object["Add"] as? NSDictionary{
if let address = addressobj["address"] as? String{
self.addr = address
print("sdfadsf \(self.addr)")
}
}
if let name = object["Name"] as? String{
self.impname = name
print("rturrty \(self.impname)")
self.retrieveLocation()
}
}
}
}
func retrieveLocation(){
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(addr, completionHandler: {(placemarks, error) -> Void in
if((error) != nil){
print("Error", error)
}
if let placemark = placemarks?.first {
let coordinates = PFGeoPoint(location: placemark.location)
if(whatever is true){
append the name and address into an array. This is the part where I just get repeats of the LATEST imported object.
}
}
})
}
最佳答案
如果您使用局部变量并将该局部变量传递给以字符串作为参数的retrieveLocation的实现,这应该可以工作retrieveLocation(address: String)
let query = PFQuery(className: "Animals")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) in
if(error == nil){
for object in objects!{
if let addressobj = object["Add"] as? NSDictionary{
if let address = addressobj["address"] as? String{
let newAddress = address
print("sdfadsf \(self.addr)")
}
}
if let name = object["Name"] as? String{
self.impname = name
print("rturrty \(self.impname)")
self.retrieveLocation(newAdress)
}
}
}
}
func retrieveLocation(address: String){
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in
if((error) != nil){
print("Error", error)
}
if let placemark = placemarks?.first {
let coordinates = PFGeoPoint(location: placemark.location)
if(whatever is true){
append the name and address into an array. This is the part where I just get repeats of the LATEST imported object.
}
}
})
}
问题似乎是,当在 geocodeAdresString 方法中使用 self.addr
时,for 循环已完成,因此覆盖了在某个时刻单独保存的所有先前值self.addr
。通过使用局部变量,每次执行时都会使用唯一的值来 geocodeAddressString
关于ios - 为什么该方法要在最后运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36779896/