问题
I got a NSMutableArray which I want to add strings to. I need to check if that string already exists on the array before adding ths string to it. Does anyway know a good way to do it?
Thanks!
回答1:
If order doesn't matter, the simplest way would be to switch to using an NSMutableSet. Sets are unordered and NSSets and NSMutableSets can contain each object only once. Only a counted set (NSCountedSet) can contain the same object multiple times.
If order does matter, continue using NSMutableArray, and use -containsObject:
to check that the object is not already there before adding it.
Edit: And as of Lion, we now have NSOrderedSet and NSMutableOrderedSet! Chocolate in my peanut butter! Peanut butter in my chocolate!
Like an unordered set, you get fast membership testing, the prohibition of duplicates, and, of course, set operations (union, intersection, etc.). Like an array, you get ordered access, including both reliable-order enumeration and access by index.
So, if you need to reject duplicates but at the same time preserve order, Lion's NS{,Mutable}OrderedSet classes are for you.
回答2:
If you just want to do what you stated once, just use containsObject:
, as in
if (![myArray containsObject:theObject]) [myArray addObject:theObject];
Note that this does a linear search through the array, and thus isn't appropriate if you're going to be using this operation a lot. If you are, and you don't need ordering, you should use NSSet
. If you do need ordering, you could use both an NSArray
and NSSet
that are kept in sync (e.g. always add/delete the same object from both collections at the same time).
回答3:
I preferred the NSPredicate which describe in here
In short
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"Ben", @"Adam", @"Melissa", nil];
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", your_search_key];
NSArray *beginWithB = [array filteredArrayUsingPredicate:bPredicate];
if ([beginWithB count] > 0)
{
//Handle duplicate
}
来源:https://stackoverflow.com/questions/4116434/check-for-duplicate-nsstrings-on-a-nsmutablearray