使用搜索栏时,tableview中的项目重复

时间:2016-06-06 01:12:18

标签: ios swift uitableview uisearchbar

这是我使用的搜索栏代理

 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,但它没有用。

知道是什么导致这种情况,我该如何解决?

1 个答案:

答案 0 :(得分:1)

你应该多加一行代码:

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