views:

161

answers:

1

Okay, so I have a UITableView that I want to apply themes to. I think I've figured out how to do it. What I do is when my view loads, I call a function called "[self getValues]". Here is how it looks:

 - (void)getValues {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *theme = [defaults valueForKey:@"theme"];
    fileName = [NSString stringWithFormat:@"%@.png", theme];
    textColor = [self getTextColor];
}

The fileName and textColor variables are defined in the header, as an NSString and UIColor. fileName is used for getting the filename of the background image I assign to the cells. I assign "textColor" to the output of the function [self getTextColor]. Here is that function:

 - (UIColor*)getTextColor {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *theme = [defaults valueForKey:@"theme"];

    NSArray *themes = [NSArray arrayWithObjects:@"Crash Love", @"DECEMBERUNDERGROUND", @"Sing the Sorrow", nil];
    NSArray *textColors = [NSArray arrayWithObjects:gold, [UIColor blackColor], [UIColor whiteColor], nil];

    int r;
    UIColor *clr;

    for (NSString *element in themes) {
        r += 1;

        if ([element isEqualToString:theme]) {
            clr = [textColors objectAtIndex:r];
            break;
        }
    }

    return clr;
}

But for some odd reason, the function above crashes. I know for sure that there is something in the function that is causing the crash, as the app works fine when I delete the line where I call the function. I've used NSLog to see what my app is getting for the theme variable, and it is either "1Theme" or the others, so that's not the problem.

Any ideas?

A: 

How about this instead:

- (UIColor*) getTextColor
{
    NSDictionary* themeColors = [NSDictionary dictionaryWithObjectsAndKeys:
        [UIColor redColor], @"Theme1",
        [UIColor blackColor], @"Theme2",
        [UIColor whiteCOlor], @"Theme3",
        nil];

    return [themeColors objectForKey: [[NSUserDefaults standardUserDefaults] valueForKey:@"theme"]];
}

The colors are stored in a dictionary so that you can simply do a lookup by name. If you call this really often then you can also consider to make the themeColors variable static and initialize it only once. Otherwise I would not bother.

St3fan
This works great! Thanks a ton!