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.
views:
798answers:
2
+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
2009-11-03 21:14:42
This is a better memory management way to do things, but I do like Dave DeLong's post about Predicates.
Pselus
2009-11-04 02:46:04
+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
2009-11-03 21:15:18
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
2009-11-03 21:19:24
read the Docs for `filteredArrayUsingPredicate` and `NSPredicate predicateWithFormat`
mga
2009-11-03 21:20:45
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
2009-11-03 21:27:44
@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
2009-11-03 21:29:37
Good and clean code! However, not memory efficient as it creates a new array with all the filtered elements.
notnoop
2009-11-03 21:31:22
@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
2009-11-03 21:35:00
@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
2009-11-03 21:53:20
What about speed? Anyone know how it would compare to a fast enumeration?
mahboudz
2009-11-03 22:00:51