Swift 按顺序执行函数调用
每次用户编辑文本字段并根据输入搜索用户时,我都尝试获取用户输入。在搜索函数的开头,我删除了users数组并执行搜索。但是,该函数是并发调用的,它甚至在执行搜索之前就清空了数组。这可能会导致用户数组中出现重复数据。有没有办法序列化整个函数调用?我查阅了GCD文档并尝试实现一些方法,但没有成功 这是源代码Swift 按顺序执行函数调用,swift,asynchronous,grand-central-dispatch,Swift,Asynchronous,Grand Central Dispatch,每次用户编辑文本字段并根据输入搜索用户时,我都尝试获取用户输入。在搜索函数的开头,我删除了users数组并执行搜索。但是,该函数是并发调用的,它甚至在执行搜索之前就清空了数组。这可能会导致用户数组中出现重复数据。有没有办法序列化整个函数调用?我查阅了GCD文档并尝试实现一些方法,但没有成功 这是源代码 // handles editting movement of the search textfield @objc func textIsChanging(){ //need to s
// handles editting movement of the search textfield
@objc func textIsChanging(){
//need to serialize execution to avoid concurrency.
// wait until previous call completes?
searchUsers()
}
// search user from database.
private func searchUsers(){
// empty user array and reload table view
removeUsers()
if let searchText = searchField.text?.lowercased() {
// search with starting index..
Api.User.queryUsersWithStartText(withText: searchText) { (user) in
if(CurrentUserInfo.uid != user.uid){
self.users.append(user)
self.tableView.reloadData()
}
}
}
}
您可以使用
DispatchGroup
按顺序执行异步函数。您需要确保DispatchGroup
上的enter()
和leave()
调用是平衡的,如果这样做,则DispatchGroup.notify(queue:DispatchQueue.main){…}
中的代码只有在DispatchGroup
中当前存在块时才会执行,因此可以安全地添加另一个块。通过从dispatchGroup.notify
内部调用searchUsers()
,可以确保只在上一次调用完成后调用该函数
let dispatchGroup = DispatchGroup()
@objc func textIsChanging(){
dispatchGroup.notify(queue: DispatchQueue.main) {
searchUsers()
}
}
// search user from database.
private func searchUsers(){
dispatchGroup.enter()
// empty user array and reload table view
removeUsers()
if let searchText = searchField.text?.lowercased() {
// search with starting index..
Api.User.queryUsersWithStartText(withText: searchText) { (user) in
if(CurrentUserInfo.uid != user.uid){
self.users.append(user)
self.tableView.reloadData()
}
dispatchGroup.leave()
}
} else {
dispatchGroup.leave()
}
}
您正在清除用户数组,然后请求查找单个用户。你怎么能得到复制品?您有一个空数组,只获取一个user@chan请注意,
serialization
标记用于回答有关将数据结构转换为文本的问题(例如JSONSerialization
),您的问题是关于函数的顺序执行。