How to return string from "for loop"? Objective-C iOS

118 views Asked by At

I'm new in programming in Objective-C language.

I need to return this "tabName" from for loop in function. How to compare that app_additional_tab_name_ is equal to tabName? Because now is still return last name for any app_additional_tab_name_.

+ (NSString *)additionalTabName {
    for (int i = 0; i <= 16; i++) {
    tabNameConcatString = [NSMutableString stringWithFormat:@"app_additional_tab_name_%d", i];
    tabName = [LocalizedStringsUserDefaults valueForKey:tabNameConcatString];
        if ([LocalizedStringsUserDefaults existsObjectForKey:tabNameConcatString])  {
            tabName = [LocalizedStringsUserDefaults valueForKey:tabNameConcatString];
            NSLog(@"This tabName is: @% @% @% @%", tabName, @" and will append to: ", tabNameConcatString);
        }
    }
    return tabName;
}

All the best.

1

There are 1 answers

0
Teja Nandamuri On BEST ANSWER

Move return inside the matching condition

+ (NSString *)additionalTabName {
    for (int i = 0; i <= 16; i++) {
    tabNameConcatString = [NSMutableString stringWithFormat:@"app_additional_tab_name_%d", i];
    tabName = [LocalizedStringsUserDefaults valueForKey:tabNameConcatString];
        if ([LocalizedStringsUserDefaults existsObjectForKey:tabNameConcatString])  {
            tabName = [LocalizedStringsUserDefaults valueForKey:tabNameConcatString];
            NSLog(@"This tabName is: @% @% @% @%", tabName, @" and will append to: ", tabNameConcatString);
            return tabName;
        }
    }
    return nil;
}

if no matches are found, you can either return nil or return empty string.