简体   繁体   English

对象未添加到数组中-Swift iOS

[英]objects not being added to an array - swift iOS

I'm trying to add Task objects to an array called tasks, and then filtered them into another array called filteredTasks by category. 我试图将Task对象添加到一个名为task的数组,然后按类别将它们过滤到另一个名为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()
}

The numbers 1,2,3, and 4 all print out in the console, but if I try to print out tasks or filteredTasks, I get [] and a count of 0. Is there a reason why tasks aren't being added to the arrays? 数字1,2,3和4都在控制台中打印出来,但是如果我尝试打印任务或filteredTasks,则会得到[]并计数为0。是否有未将任务添加到其中的原因?数组?

You can't do it that way. 你不能那样做。 The method observeEventType is asynchronous. 方法observeEventType是异步的。 It takes a closure as a parameter. 它以闭包作为参数。 It returns immediately, before the closure is run. 在关闭运行之前,它将立即返回。

You need to rewrite your loadTasks function to also take a completion closure. 您需要重写您的loadTasks函数,以完成关闭。 You'd then call it with the code that you want to execute once the tasks array is filled. 任务数组填充后,您便可以使用要执行的代码来调用它。 See my answer to this thread for a working example: 有关工作示例,请参见我对此线程的回答:

how to return value after the execution of the block? 块执行后如何返回值? Swift 迅速

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SWIFT:当将 Firebase 信息映射到 object 时,对象一旦返回就不会被添加到数组中,为什么? - SWIFT: When mapping Firebase info to an object the objects are not being added to the array once returned, why? 解析查询结果未添加(附加)到iOS Swift中的本地数组 - Parse query results aren't being added (appended) to a local array in iOS Swift 添加到子视图的数组对象不出现(Swift 3) - Array objects added to subview not appearing (swift 3) iOS-将数据添加到数组后让Segue执行(Swift) - iOS- make Segue perform after data is added to array (Swift) Swift iOS-将数组过滤为类似对象的数组 - Swift iOS - Filter array into array of array like objects iOS Swift:符合协议的对象数组:如何检查数组是否包含 - iOS Swift: Array of Objects conforming to a Protocol: How to check if array contains 如何从第二个数组中的第一个数组中找到对象? 迅捷的iOS - How to find objects from first array in second array? Swift iOS iOS-对象被释放? - iOS - Objects being released? 如何在Swift iOS中从Dictionary中保存和检索对象数组值? - How to save and retrieve Array of Objects value from Dictionary in Swift iOS? 如何正确发送带有对象的数组 JSON Swift iOS - How to correctly send array with objects in JSON Swift iOS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM