views:

20

answers:

1

I have the following method:

-(UIImage *)flagFromOrigin:(NSString *)originString {
        NSRange range;
        for (NSString *arrayString in countryArray) {
            range = [[originString lowercaseString] rangeOfString:arrayString];
            if (range.location != NSNotFound) {
                return [UIImage imageNamed:[NSString stringWithFormat:@"%@.png", arrayString]];
            }
        }
        return nil;
    }

Earlier in the class I init an NSArray *countyArray and add file names (@"united states", @"canada", @"germany", @"denmark", etc.).

I was hoping someone could tell me a better way so I don't have to create the array to loop through, but if I could instead look directly at the file names? This way I don't have to add 200+ NSString objects to the array and possible overlook a whole bunch.

Thanks

A: 

It looks like you're trying to return an image for a country, but only if it's in your approved list, with the possibility of originString containing other text that you don't care about.

Instead, if possible I'd make it a requirement that originString only contains the text you care about, then move those images into a subdirectory of your resources, and call imageNamed: directly. It'll return nil if the image could not be loaded and will behave the same as your method does. You can get rid of that array and avoid the loop and lots of string comparisons.

If you can't add that requirement for originString, then I suggest that's a design issue you should consider fixing first.


Edit based on Canada Dev's reply:

Look at the documentation for -[NSFileManager contentsOfDirectoryAtPath:error:]. You can enumerate the files in a directory, storing them (minus the .png extension) in an array, then use that array to scan for matches.

You should sort the array by length, longest first, to avoid false positives. I can't think of an example for countries, but for states you'd want to check "West Virginia" before "Virginia", because the latter will match strings that also match the former.

Steve Madsen
That would still require me to make `originString` contain an appropriate country. I already have 200+ image files, I just want to look for an image file that would match the originString, which may contain more than the raw country string, hence the loop.
Canada Dev