views:

798

answers:

2

What is the most memory efficient way to loop through an NSMutableArray of custom objects? I need to check a value in each object in the array and return how many of that type of object is in the array.

+6  A: 
for (WhateverYourClassNameIs *whateverNameYouWant in yourArrayName) {
    [whateverNameYouWant performSelector];
    more code here;
}

It's called fast enumeration and was a new feature with Objective C 2.0, which is available on the iPhone.

refulgentis
This is a better memory management way to do things, but I do like Dave DeLong's post about Predicates.
Pselus
+8  A: 

I'd probably just use a predicate, which would be something like this:

NSArray * filtered = [myArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"aProperty = %@", @"someValue"]];
NSLog(@"number of items where aProperty = someValue: %d", [filtered count]);

Edit: This code is functionally equivalent to:

NSMutableArray * filtered = [NSMutableArray array];
for (MyCustomObject * object in myArray) {
  if ([[object aProperty] isEqual:@"someValue"]) {
    [filtered addObject:object];
  }
}
Dave DeLong
Care to give a little explanation of this chunk of code? I'm an iPhone newbie and an Obj-C newbie. Your code looks small and awesome, but I hate using things I don't understand.
Pselus
read the Docs for `filteredArrayUsingPredicate` and `NSPredicate predicateWithFormat`
mga
@Pselus - edited answer
Dave DeLong
Thanks for the explanation, that's amazing. I just started using predicates after moving from writing games to doing Core Data-based stuff, but I had know idea they were that powerful.
refulgentis
@refulgentis - once you get the hang of predicates (which are totally awesome, btw), have fun wrapping your head around keypaths. I've just started getting into those recently, and they are SO MUCH FUN. =D
Dave DeLong
Good and clean code! However, not memory efficient as it creates a new array with all the filtered elements.
notnoop
@notnoop, true, but the overhead is very minimal, since the new array just holds pointers to pre-existing objects. I'd guess it'd only add at most a couple hundred bytes to the overall memory usage. However, given that the question asked for the "most memory efficient" way, I'll give you this one. ;)
Dave DeLong
Dave, does aProperty need to be KVC compliant for this to work?
nall
@nall - I don't believe so. I'm *pretty sure* that you can even run this for things like `@"description CONTAINS NSObject"` or whatever. I believe it just executes a selector with the name of the LHS and compares the return values.
Dave DeLong
What about speed? Anyone know how it would compare to a fast enumeration?
mahboudz