开发者

removeAllObjects not removing if action is fast

开发者 https://www.devze.com 2023-02-16 22:27 出处:网络
I a开发者_如何转开发m using a search bar in my app and display some results below from an ext API.

I a开发者_如何转开发m 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.


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.


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号