7

Using LINQ in .Net I can select items from an array that match a particular criteria i.e. from an array called People:

var cleverPeople = People.Where(o=>o.IQ>110);

Is there anything similar I can do to an NSMutableArray? I have many items in it and enumerating it with a loop is pretty costly performance wise.

4 Answers 4

7

See -[NSArray filteredArrayUsingPredicate:].

Sign up to request clarification or add additional context in comments.

3 Comments

beautiful. exactly what I needed. NSPredicate *pred = [NSPredicate predicateWithFormat:@"isFired == NO"]; NSArray *filtered = [self.arenamap filteredArrayUsingPredicate:pred];
Here's a nice write-up on NSPredicate vs LINQ. cimgf.com/2008/08/24/…
Note that this will probably not be much faster than iterating the loop yourself. Fundamentally to select items from an array like this, the whole array must be iterated over somewhere along the line
4

I have created a simple library, called Linq to ObjectiveC, which is a collection of methods that provide a Linq-style query interface. In your case you need the Linq-to-ObjectiveC where method:

NSArray* peopleWhoAreSmart = [people where:^BOOL(id person) {
    return [[person iq] intValue] > 110;
}];

This returns an array of of people where their IQ > 110.

1 Comment

Nice — good tip. The lack of these obvious methods in Cocoa's collection classes is mind-boggling. (Also, funnily enough, this wouldn't have been possible when the question was originally posted, as blocks weren't around yet. Yay progress.)
0

Another option would be to use Higher Order Messaging to implement select. For example,

NSArray* cleverPeople = [[People select] greaterIQ:110];

Where greaterIQ would be a category method on People.

Comments

0

Of course these (10.6+) days we've got nice APIs like indexOfObjectPassingTest to do things like

var smartPeople = [People indexesOfObjectsPassingTest:^BOOL(id person, NSUInteger idx, BOOL *stop)
                  {  return person.iq > 110; } ];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.