gpt4 book ai didi

ios - 使用搜索栏时 TableView 中的重复项

转载 作者:可可西里 更新时间:2023-11-01 02:16:43 24 4
gpt4 key购买 nike

这是我使用的搜索栏委托(delegate)

 func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.characters.count >= 2 {
self.setupinbox(searchText)
}
}

这是从服务器获取数据的函数

func setupinbox(q : String) {

arrayOfRels.removeAll(keepCapacity: false)
self.tableView.reloadData()

let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "URL")!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
let data = "devicetoken=\(devicetoken!)&q=\(q)&user_id=\(userid)"
request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding)

let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}

if let response = response {

let res = response as! NSHTTPURLResponse

dispatch_async(dispatch_get_main_queue(), {
if (res.statusCode >= 200 && res.statusCode < 300)
{

do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSArray
let json = JSON(jsonData)

for (_, subJSON): (String, JSON) in json[0]["interests"] {

let title = subJSON["title"].string
let eID = subJSON["ID"].string
let count = subJSON["count"].string
let rel1 = InboxInterests(title: title!,eventID : NSInteger(eID!)!, count: count!)
self.arrayOfRels.append(rel1)

}

} catch let error as NSError {
print(error)
}

self.tableView.reloadData()

} else {

let alert = UIAlertController(title: "Error", message: "Connection Failed", preferredStyle: .Alert)

alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction) in

}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
)}
})
task.resume()

}

当我慢慢输入搜索栏时,一切正常,我看到的结果是正确的。

但是当我快速输入 2 个字母时,我得到了重复项。

enter image description here

当我快速删除字母时,我也会得到重复的项目

尝试了诸如延迟 textDidChange 之类的方法,但没有成功。

知道是什么原因造成的吗?我该如何解决?

最佳答案

你应该多加一行代码:

do {
arrayOfRels.removeAll(keepCapacity: false)
........

关于ios - 使用搜索栏时 TableView 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37648348/

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