gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:34:26 25 4
gpt4 key购买 nike

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

当我运行应用程序并更新任务时,每当我对任务执行任何操作时,它都会打印“fetchAllTask​​sInTeam called”,告诉我 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
}

最佳答案

当您调用 fetchAllTask​​sInTeam 时,您正在设置 observeEventType(.Value。这意味着每当您的 firebase 数据库的特定分支发生更改时,都会触发一个事件并回调你用 withBlock: { snapshot in .. 设置将被调用。这就是它打印 fetchAllTask​​sInTeam called 的原因。

因此,调用的不是 fetchAllTask​​sInTeam,而是您的观察者回调。

解决方案

您可以通过在每次触发回调时重置您的 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)
})

关于ios - 方法在操作中复制数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38211796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com