I have an NSArray
of NSDictionary
.
Each dictionary in the array has three keys: 'Name', 'Sex' and 'Age'
How can I find the index in NSArray
of NSDictionary
where, for example, Name = 'Roger'
?
On iOS 4.0 and up you can do the following:
- (NSUInteger) indexOfObjectWithName: (NSString*) name inArray: (NSArray*) array
{
return [array indexOfObjectPassingTest:
^BOOL(id dictionary, NSUInteger idx, BOOL *stop) {
return [[dictionary objectForKey: @"Name"] isEqualToString: name];
}];
}
Elegant, no?
NSUInteger count = [array count];
for (NSUInteger index = 0; index < count; index++)
{
if ([[[array objectAtIndex: index] objectForKey: @"Name"] isEqualToString: @"Roger"])
{
return index;
}
}
return NSNotFound;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With