Jan
11
2012

Finding Next Available Name in Objective-C



Comments available as RSS 2.0

Useful method for finding the next available unique name in a batch of strings.

Eg: give it A list of { “Name”, “Name 1″, “Name 2″ } and it will return “Name 3″.

+(NSString*)getNextAVailableName:(NSString*)name fromNames:(NSMutableArray*)otherNames {
    if ([otherNames indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [[name lowercaseString] isEqualToString:(NSString*)obj];
    }] == NSNotFound) {
        return name;
    }
    bool gotName=false;
    NSString *currentName = name;
    for(int i = 2; !gotName; ) {
        currentName = [NSString stringWithFormat:@"%@ %d", name , i];
        if([otherNames indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
            return [[currentName lowercaseString] isEqualToString:(NSString*)obj];
        }] != NSNotFound) {
            i++;
        } else {
            name = currentName;
            gotName = true;
        }
    }
    return name;
}

Comments

Leave a Comment

Login using OpenID or enter your details below to leave a comment.

OpenID
Anonymous


Comment