方法在操作中复制数组中的项目

时间:2016-07-05 20:03:49

标签: ios arrays swift firebase firebase-realtime-database

我有一系列与Firebase同步的任务。当我调用更新“完成”和“完成”属性的方法时(在用户检查项目之后),它会复制数组中的所有任务(但不会复制到firebase上)。基本上它调用fetchAllTasksInTeam中的方法(viewDidLoad)来获取给定团队的所有任务,这是奇怪的,因为viewDidLoad只应被调用一次。我也尝试将这些方法放在viewDidAppear中,它给了我相同的结果。

当我运行应用程序并更新任务时,每次我对任务执行任何操作时都会打印“fetchAllTask​​sInTeam”,告诉我viewDidAppear和我的函数再次被调用。

class Firebase {

func fetchAllTasksInTeam(ref:FIRDatabaseReference, team:String, completion:(tasksArray:[Task])->()) {
   var newTasks = [Task]()                             
   ref.child("tasks").queryOrderedByChild("team").queryEqualToValue(team).observeEventType(.Value, withBlock: { snapshot in
       for task in snapshot.children {
          let tasks = Task(snapshot: task as! FIRDataSnapshot)
          newTasks.append(tasks)
       }
       print("fetchAllTasksInTeam called")
       completion(tasksArray: newTasks)
    })                                      
  }

func updateTaskDoneBool(ref:FIRDatabaseReference, taskID:String, taskDone:Bool) {                       
   ref.child("tasks").child(taskID).child("done").setValue(taskDone)   
   }

func updateTaskCompletedBy(ref:FIRDatabaseReference, taskID:String, taskCompletedBy:String) {                     
   ref.child("tasks").child(taskID).child("completedBy").setValue(taskCompletedBy)
   }
}



protocol TaskCellDelegate {
    func doneHit(cell : TaskCell)
}

class TaskCell : UITableViewCell, BEMCheckBoxDelegate {

    var delegate : TaskCellDelegate?

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var detailLabel: UILabel!
    @IBOutlet weak var _checkBox: BEMCheckBox!



    override func awakeFromNib() {
        super.awakeFromNib()
        let tap = UITapGestureRecognizer(target: self, action: #selector(TaskCell.buttonClicked(_:)))
        tap.numberOfTapsRequired = 1
        _checkBox.addGestureRecognizer(tap)
        _checkBox.userInteractionEnabled = true
        _checkBox.onAnimationType = .Fill
        _checkBox.offAnimationType = .Fade
    }


    func buttonClicked(sender:UITapGestureRecognizer) {
        delegate?.doneHit(self)

    }
}


class TasksTVC: UITableViewController, TaskCellDelegate {


    var ref:FIRDatabaseReference!
    let fb = Firebase()
    var currentUser = FIRAuth.auth()?.currentUser
    var cell = TaskCell()
    var task:Task!
    var user = ""
    var team = ""
    var service = ""
    var position = ""
    var _time = [NSDate]()
    var nineTimes = [String]()
    var noonTimes = [String]()
    var fiveTimes = [String]()
    var sectionTimes = [String]()
    var tasksInSectionArray = [[Task]]()
    var convertedTimeString = [String]()
    var tasks = [Task]() {
        didSet {
            updateTableView()
            convertTime(sectionTimes)
            tableView?.reloadData()
        }
    }

    override func viewDidAppear(animated: Bool) {
        fb.fetchCurrentUser(ref, currentUser: currentUser) { (service, position) in
            self.service = service
            self.position = position
        }
        fb.fetchAllTasksInTeam(ref, team: team) { (tasksArray) in
            print("\(tasksArray.count) tasks")
            self.tasks = tasksArray
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        ref = FIRDatabase.database().reference()

        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 44.0
    }


    // MARK: - TaskCellDelegate

    func doneHit(cell:TaskCell) {
        if let ip = tableView.indexPathForCell(cell) {
            task = tasksInSectionArray[ip.section][ip.row]
            if task.done == false {
                cell._checkBox.setOn(true, animated: true)
                task.done = true
                task.completedBy = user
                cell.detailLabel.text = "Completed By: \(task.completedBy)"
                cell.label.textColor = UIColor.grayColor()
                print("cell checked")
            }
            else {
                cell._checkBox.setOn(false, animated: true)
                task.done = false
                task.completedBy = ""
                cell.detailLabel.text = ""
                cell.label.textColor = UIColor.blackColor()
                print("cell unchecked")

            }
            fb.updateTaskDoneBool(ref, taskID: task.id, taskDone: task.done)
            fb.updateTaskCompletedBy(ref, taskID: task.id, taskCompletedBy: task.completedBy)
        }

    }


    // Converting time to be shown in sections
    func convertTime(dueTimes:[String]) {
        let timeFormatter = NSDateFormatter()
        timeFormatter.dateFormat = "HH:mm"
        if position != "Staff" {
            if service == "9AM" {
                _time = nineTimes.map{timeFormatter.dateFromString($0)!}
            }
            else if service == "12PM" {
                _time = noonTimes.map{timeFormatter.dateFromString($0)!}
            }
            else if service == "5PM" {
                _time = fiveTimes.map{timeFormatter.dateFromString($0)!}
            }
            else {
                _time = sectionTimes.map{timeFormatter.dateFromString($0)!}
            }
        }
        timeFormatter.dateFormat = "h:mm a"
        convertedTimeString = _time.map{timeFormatter.stringFromDate($0)}
    }

    func updateTableView() {
        sectionTimes = Set(tasks.map{$0.dueTime}).sort()
        groupTimes()
        if service == "9AM" && position != "Staff" {
            tasksInSectionArray = nineTimes.map{section in tasks.filter{$0.dueTime == section}}
        }
        else if service == "12PM" && position != "Staff" {
            tasksInSectionArray = noonTimes.map{section in tasks.filter{$0.dueTime == section}}
        }
        else if service == "5PM" && position != "Staff" {
            tasksInSectionArray = fiveTimes.map{section in tasks.filter{$0.dueTime == section}}
        }
        else {
            tasksInSectionArray = sectionTimes.map{section in tasks.filter{$0.dueTime == section}}
        }
    }


    // MARK: - Table view data source

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return convertedTimeString[section]
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return tasksInSectionArray.count
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasksInSectionArray[section].count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! TaskCell
        cell.selectionStyle = .None
        task = tasksInSectionArray[indexPath.section][indexPath.row]
        cell.label.text = task.title
        if task.done == true {
            cell._checkBox.setOn(true, animated: true)
            cell.detailLabel.text = "Completed By: \(task.completedBy)"
            cell.label.textColor = UIColor.grayColor()
        }
        else {
            cell._checkBox.setOn(false, animated: true)
            cell.detailLabel.text = ""
            cell.label.textColor = UIColor.blackColor()

        }
        doneHit(cell)
        cell.delegate = self
        return cell
    }

1 个答案:

答案 0 :(得分:0)

当您致电fetchAllTasksInTeam时,您正在设置observeEventType(.Value。这意味着每当firebase数据库的特定分支发生更改时,将触发事件,并且将调用您使用withBlock: { snapshot in ..设置的回调。这就是打印fetchAllTasksInTeam called的原因。

因此,它不是被调用的fetchAllTasksInTeam,而是你的观察者回调。

解决方案

每次触发回调时,您都可以通过重置newTasks数组来解决此问题。在当前情况下,您的回调只是将数据推送到它而不清除旧值。

ref.child("tasks").queryOrderedByChild("team").queryEqualToValue(team).observeEventType(.Value, withBlock: { snapshot in
    var newTasks = [Task]() 
    for task in snapshot.children {
        let tasks = Task(snapshot: task as! FIRDataSnapshot)
        newTasks.append(tasks)
    }
    print("callback called")
    completion(tasksArray: newTasks)
})