Question

I have an NSArray of objects each of with contain a "key" field

I have another NSArray with nested NSArrays grouping those objects by a different field "group by field" for instance a display name (alphabetic grouping)

For instance

@interface MyObject

@property (nonatomic) int key;
@property (nonatomic,strong) NSString *groupByKey;

@end


NSArray *aBounchOfObjectsInAFlatList = @[obj1,obj2,obj3....];

NSArray *groupByArrayOfObjects = @[@[obj1_tag,obj2_tag],@[objn_tag,objk_tag]....];

Important to note that obj1 != obj1_tag - they only share values of "groupByKey" and/or "key".

I would like to find the index of each obj_tag where (obj_tag.key == obj.key) from the flat array.

Now I am running 2 loops and saving the counter values - creating index paths for the matches.

I assume there is a clear way using NSPredicates to create an array of NSIndexPaths for the corresponding objects but I am not clear how to do this

Was it helpful?

Solution

NSPredicate is just a predicate and nothing more. It is applied to some object and yields YES or NO. A predicate can be used for filtering an array, but since the predicate itself is applied to each single array element, it does not "know" the location (or index) of the object being tested. Therefore a NSPredicate cannot create an array of NSIndexPaths.

The NSArray method indexOfObjectPassingTest: can be useful to find the location of an object in an array, but even that method has to loop over all array elements to find the object. So it might help to make the code shorter or better readable, but it does not change the performance.

If groupByArrayOfObjects is really large, then you can create a mapping (an NSDictionary) from each key to the corresponding index path first. This requires only one enumeration of the (nested) array. Then you can use this mapping to get the index path for each element in the other array aBounchOfObjectsInAFlatList.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top