How to find a custom-object-property value in a NSArray?
Well, use this Objective-C method!
/** Search a string in an array of objects.
@param what String value to look for.
@param arr Array to search in.
@param property String representing property to use in comparision
@return Returns the index of first item found or -1 if not found.
@see searchForInteger:inArray:usingProperty:
@see searchForFloat:inArray:usingProperty:
@see searchForBool:inArray:usingProperty:
*/
+ (NSInteger)searchForString:(NSString *)what inArray:(NSArray*)arr usingProperty:(NSString *)property {
NSInteger ret = -1;
// Create an array to store all items that meet the criteria "item.property == what".
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", property, what];
NSArray *tmp = [arr filteredArrayUsingPredicate:predicate];
if ([tmp count] <= 0) {
return ret;
}
for (NSInteger i=0; i<[arr count]; i++) {
if ([arr objectAtIndex:i] == [tmp objectAtIndex:0]) { // Compare only the first item of tmp array.
ret = i;
break;
}
}
return ret;
}
Download the ready-for-use source file (.m) of Search custom Object property in a NSArray (NSString version)
No comments:
Post a Comment