Utku Dalmaz Utku Dalmaz - 1 year ago 101
iOS Question

Duplicate item in tableview when using searchbar

This is the searchbar delegate that i use

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

This is the function to get data from server

func setupinbox(q : String) {

arrayOfRels.removeAll(keepCapacity: false)

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 {

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!)


} catch let error as NSError {


} 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)


When i type searchbar slowly, everything is ok, i see results correctly.

But when i type 2 letters very quickly, i get duplicate item.

enter image description here

I also get duplicate items when i remove letters quickly

Tried something like delaying the
but it didnt work.

Any idea what causes this and how can i fix?

Answer Source

You should put an extra line of code:

do {
arrayOfRels.removeAll(keepCapacity: false)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download