Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search NSArray for value matching value

Tags:

I have an NSArray of objects, which has a particular property called name (type NSString).
I have a second NSArray of NSStrings which are names.

I'd like to get an NSArray of all the objects whose .name property matches one of the names in the second NSArray.

How do I go about this, fast and efficiently as this will be required quite often.

like image 684
Jonathan. Avatar asked Mar 07 '11 21:03

Jonathan.


People also ask

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What is NSArray Objective C?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.


1 Answers

Why not just to use predicates to do that for you?:

// For number kind of values: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF = %@", value]; NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];  // For string kind of values: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", value]; NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];  // For any object kind of value (yes, you can search objects also): NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", value]; NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate]; 
like image 98
Lukasz Avatar answered Sep 19 '22 12:09

Lukasz