如果这是一个非常基本的问题,我深表歉意,我是Swift和Firebase的新手。我有一个待办事项列表应用程序,它使用Firestore作为后端。将来,我计划为共享的任务列表添加多用户支持。
我遇到的问题是,当我使用loadItems()和loadSections()函数刷新tableView时,数组被复制了。这样会产生奇怪的效果。
链接到屏幕记录:https://www.dropbox.com/s/cd9084skr2x26li/Screen%20Recording%202020-07-21%20at%2017.51.07.mov?dl=0
我的loadItems()和loadSections()
//MARK: - Load sections
func loadSections(listID: String) {
// print("Loading sections...")
let listRef = db.collection(K.FStore.lists).document(listID)
listRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
let sectionNames = document.data()![K.List.sections] as? [String]
self.sections.removeAll()
if let sectionNames = sectionNames {
for (index, item) in sectionNames.enumerated() {
let newSection = Section(name: item, isExpanded: true, items: [])
self.sections.append(newSection)
self.loadItems(listID: listID, section: index)
}
}
self.tableView.reloadData()
} else {
print("Document does not exist")
}
}
}
//MARK: - Load items
func loadItems(listID: String, section: Int) {
var newItems = [Task]()
// self.sections[section].items.removeAll()
let itemRef = db.collection(K.FStore.lists).document(listID).collection(K.FStore.sections).document("\(section)").collection(K.FStore.items)
itemRef.addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
for document in documents {
print("Name: \(document.data()[K.Item.name])")
let name = document.data()[K.Item.name] as! String
let isChecked = document.data()[K.Item.isChecked] as! Bool
let documentID = document.documentID as! String
let newTask = Task(name: name, isChecked: isChecked, itemID: documentID)
newItems.append(newTask)
}
self.sections[section].items.removeAll()
if section == 2 {
print(newItems.count)
}
self.sections[section].items = newItems
self.tableView.reloadData()
} }
我的viewDidLoad()(我在其中调用该函数)
var sections: [Section] = []
// Database references
let db = Firestore.firestore()
var items: [Task]?
override func viewDidLoad() {
super.viewDidLoad()
// Storing user variables locally
let user = Auth.auth().currentUser
if let user = user {
currentUserID = user.uid
userRef = db.collection(K.FStore.users).document(currentUserID!)
userRef!.getDocument { (snapshot, error) in
if let data = snapshot?.data() {
self.userFirstName = (data[K.User.firstName] as! String)
self.userEmail = (data[K.User.email] as! String)
self.currentLists = (data[K.User.lists] as! [String])
self.currentListID = self.currentLists![0]
self.listsRef = self.db.collection(K.FStore.lists).document(self.currentListID!)
// Load the section names
self.loadSections(listID: self.currentListID!)
} else {
print("Could not find document")
}
}
} }
在我的addTask()和checkTask()中,我将此函数称为
func refreshTable() {
loadSections(listID: currentListID!)
tableView.reloadData()
}
我将如何解决此问题?
非常感谢, 马特