views:

161

answers:

3

Example:

I have an NSArray with 40 objects. What is the most efficient way to return ONLY those objects with index equal to a number specified in another NSArray (e.g {0, 27, 36} for example)?

Can a predicate be used here? Or is there a more simple and efficient approach?

+3  A: 

Why don't you just iterate over the index array and look up each index in the data array replacing the index with the looked-up object.

In the end, the array that held the indices now holds the objects. If you don't want to wipe out your index array, then just create a new array of the same size as the index array and put the objects there.

You might be over-thinking the design of this and falling prey to micro-optimization. (Which is a bad thing.)

Ben S
I just thought there might be a simple one-liner (e.g. NSArray filterByIndexes:self.IndexNumbers). Could always add this as a category for both NSArray and NSMutableArray ... but I didn't want to re-invent the wheel (if indeed it already exists)
wgpubs
A: 

I remember reading one time, and I cant say where but it stuck in my mind, that if this was something you need to do many times and the array is fairly large that there is a more efficient way. You could create a new dictionary from that array where each entry has the key of the index number and the value is the array item. You only create the dictionary once so the hard work is over in one shot. Then every time you need to access values at certain indexes you just ask for valueForKey:@"indexNumber". But I never had a need for this so I never tested if it was more efficient in the long run... it's just a thought.

regulus6633
+2  A: 

There is a method (objectsAtIndexes) for returning specified indexes from an original array, but it requires an NSIndexSet as its argument, and there isn't a built-in way to convert your array of indices to an index set. On the plus side, you can generate the index set with a short loop, as follows:

NSMutableIndexSet indexes = [NSMutableIndexSet indexSet];
for (NSNumber * number in indexArray)
{
    [indexes addIndex:[number intValue]];
}
return [originalArray objectsAtIndexes:indexes];

Is this any more efficient than simply looping through the original array? I have no idea. You would have to profile your app to be sure.

e.James