Since an array can only be accessed by index, iterating through the array is the only way. You can loop explicitly, looking for the appropriate object or implicitly using the indexOfObjectPassingTest
method of NSArray
. The advantage of this approach is that it only has to iterate as far as the first match, while filteredArrayUsingPredicate
needs to iterate the whole array.
NSInteger objectIndex=[myArray indexOfObjectPassingTest:^BOOL(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
CustomObject *myObject=(CustomObject *)obj;
if (obj.id==targetid) { // Assumes id is an int, change the test as appropriate if it is a string or other object
*stop=YES;
}
}];
Another approach is to use an auxiliary NSDictionary that stores the index of the object. This requires a single iteration of the array to build the dictionary but allows you to locate a given object more quickly.
For convenience I will assume that id in this case is a string; if it is an int then you need to box it in an NSNumber:
NSMutableDictionary auxDict=[NSMutableDictionary new];
for (i=0;i<myArray.count;i++) {
CustomObject *obj=myArray[i];
[auxDict addObject:[NSNumber numberWithInt:i] forKey:obj.id];
}
Then, to access an object, simply use the dictionary
NSNumber *indexNumber=auxDict[targetId];
int index=[indexNumber intValue];
CustomObject *object=myArray[index];