0

I am using a search bar in my app and display some results below from an ext API. The contents first get stored in an array "xyz" and each time the user types in the search bar, I removeAllObjects and reload the table.

The results are correct if the user types slow i.e. [xyz removeAllObjects] works fine...However if the user types very fast, [xyz removeAllObjects] does not seem to have any effect and duplicate items get appended to the array..

I am not sure how to fix this. Please help me. Thank you.

copenndthagen
  • 49,230
  • 102
  • 290
  • 442

2 Answers2

3

removeAllObjects is an entirely serial operation; that method doesn't return until the array is empty.

Therefore, there must be a thread in play and you are quite likely accessing a mutable array from multiple threads. Mutable arrays aren't thread safe. Fix the exclusivity and you'll fix your problem.

The easiest way is to separate the array being displayed from the array being computed. As soon as the computation is done, move the computed array to the display array and never mutate it again.

bbum
  • 162,346
  • 23
  • 271
  • 359
  • Oh yes..replacing the thread code with normal [self method:]; fixes the problem...However there is only 1 issue with that; The search bar gets blocked i.e. user cannot now type quickly and wait each time a letter is entered...So is there any way to get both things working at a time? – copenndthagen Mar 14 '11 at 16:44
  • I also had tried with 2 separate arrays..But that also did not work..I am trying to find a solution keeping just 1 array, so as to avoid any complexities... – copenndthagen Mar 14 '11 at 17:19
  • Why didn't two arrays work? That is the generally accepted solution in such a case. – bbum Mar 14 '11 at 20:43
2

Why not create a new NSArray, point the results at that, and then release the old array. That way having duplicates will be impossible. Something like:

NSArray *newArray = [someObject newSearchResults];
NSArray *oldArray = xyz;
xyz = [newArray retain];
[oldArray release];
Ned
  • 6,280
  • 2
  • 30
  • 34