Author Topic: How can I find a specific object in an NSMutableArray  (Read 2375 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
How can I find a specific object in an NSMutableArray
« on: August 05, 2014, 04:40:29 AM »
NSMutableArray has a powerful method called indexOfObjectPassingTest that allows you to look for an object matching a test criteria. Since NSMutableArrays often contain entity objects, I'll use an entity object as an example.

Objective-C:
Code: [Select]
NSInteger idx = [userList indexOfObjectPassingTest:^BOOL(UserEntity *obj, NSUInteger idx, BOOL *stop) {
    return [obj.userID isEqualToString:@"12345"];
 }];

if (idx != NSNotFound) {
    UserEntity *userEntity = userList[idx];
}

In this code sample, userList contains a list of UserEntity objects. We are looking for a UserEntity whose userID attribute is equal to "12345". If that UserEntity is found, then idx will not be equal to NSNotFound, but will be set to the index of the object in the list.

All the best!
Kevin
« Last Edit: July 24, 2015, 04:48:17 AM by kjmcneish »