我正在尝试将Task对象添加到名为tasks的数组中,然后按类别将它们过滤到另一个名为filteredTasks的数组中。
var tasks = [Task]()
var filteredTasks = [Task]()
override func viewDidLoad() {
super.viewDidLoad()
print(categoryPass)
loadTasks()
filterTasks(categoryPass!)
if filteredTasks.isEmpty {
filterTasks(categoryPass!)
}
print(filteredTasks)
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.locationManager.delegate = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
func loadTasks() {
var taskTitle: String?
var id: String?
var distance: Double?
var category: String?
var locationDict: [String:CLLocation] = [:]
var refHandle = self.ref.child("tasks").observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
self.tasksDict = snapshot.value as? NSDictionary
for i in 0 ..< self.tasksDict!.count {
let taskId = self.tasksDict!.allKeys[i] as! String
print ("1")
id = taskId
print (taskId)
let task = self.tasksDict!.objectForKey(taskId) as! NSDictionary
print ("2")
let lat = task.objectForKey("latitude") as! String
let long = task.objectForKey("longitude") as! String
let latNum = Double(lat)! as CLLocationDegrees
let longNum = Double(long)! as CLLocationDegrees
taskTitle = task.objectForKey("title") as? String
category = task.objectForKey("category") as? String
print("3")
// print (taskTitle)
//print (category)
let pointLocation = CLLocation(latitude: latNum, longitude: longNum)
locationDict[taskId] = pointLocation
if (self.locationCurrent == nil) {
self.locationCurrent = self.locationManager.location!
}
print("4")
distance = round(self.locationCurrent!.distanceFromLocation(pointLocation))
var taskAddition = Task(title: taskTitle, id: id, distance: distance, category: category)
print (taskAddition)
self.tasks += [taskAddition]
}
})
}
func filterTasks(searchText: String, scope: String = "All") {
print("filter")
for i in 0 ..< tasks.count {
let taskId = tasksDict!.allKeys[i] as! String
// print (taskId)
let task = tasksDict!.objectForKey(taskId) as! NSDictionary
let taskCategory = task.objectForKey("category") as! String
if (taskCategory.lowercaseString.containsString(searchText.lowercaseString)) {
filteredTasks.append(task[i] as! Task)
}
}
self.tableView.reloadData()
}
数字1,2,3和4都在控制台中打印出来,但是如果我尝试打印出任务或者过滤任务,我得到[]并且计数为0.是否有理由说明任务不是被添加到数组?
答案 0 :(得分:0)
你不能这样做。方法observeEventType
是异步的。它需要一个闭包作为参数。它会在关闭运行之前立即返回。
您需要重写loadTasks函数以完成关闭。然后,您将在填充任务数组后使用要执行的代码调用它。有关工作示例,请参阅此线程的答案: