Pages

August 12, 2013

Search custom Object property in a NSArray (CGFloat version)

How to find a custom-object-property value in a NSArray?
Well, use this Objective-C method!


/** Search a float in an array of objects.

 @param what Float 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 searchForString:inArray:usingProperty:
 @see searchForInteger:inArray:usingProperty:
 @see searchForBool:inArray:usingProperty:

 */
+ (NSInteger)searchForFloat:(CGFloat)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 == %f", 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 (CGFloat version)

No comments:

Post a Comment