views:

311

answers:

3

I'm trying to make a random image appear on the press of a button. So it generates a random number, and the switch algorithm swaps the chosen image with the one in the imgview. but I want a switch in the settings app to toggle which set of images to use. I know pretty much how to do it...it's just that it doesn't work. I'm missing some syntax thing...Please help, stackoverflow? it's my birthday.

int Number = rand() %30;

NSString *toggleValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"enabled_preference"];

switch (Number) {

        if (*toggleValue == 0) {
        case 0:
            picture.image = [UIImage imageNamed:@"1.png"];
            break;

        case 1:
            picture.image = [UIImage imageNamed:@"2.png"];

            break;}

else {

        case 0:
            picture.image = [UIImage imageNamed:@"3.png"];
            break;

        case 1:
            picture.image = [UIImage imageNamed:@"4.png"];

            break;}
}
+1  A: 

You can't put an if into a switch like this... try with this syntax instead:

if (*toggleValue == 0) 
{
    switch (Number) 
    {
        case 0:picture.image = [UIImage imageNamed:@"1.png"]; break;
        case 1:picture.image = [UIImage imageNamed:@"2.png"];break;
    }
}
else 
{
    switch (Number) 
    {
        case 0:picture.image = [UIImage imageNamed:@"3.png"];break;
        case 1:picture.image = [UIImage imageNamed:@"4.png"];break;
    }

}
Cesar
A: 
int randomInt = rand() % 30;

if (toggleEnabled) {
    switch (randomInt) {
        case 0:
            picture.image = [UIImage imageNamed:@"0.toggleEnabled.png"];
            break;    
        case 1:
            picture.image = [UIImage imageNamed:@"1.toggleEnabled.png"];
            break;
        // ...
    }
else {
    switch (randomInt) {
        case 0:
            picture.image = [UIImage imageNamed:@"0.toggleDisabled.png"];
            break;
        // ...
    }
}
Alex Reynolds
+1  A: 
NSString *toggleValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"enabled_preference"];
NSArray *imagesA = [NSArray arrayWithObjects:@"img1.png" , @"img2.png" , ... , nil];
NSArray *imagesB = [NSArray arrayWithObjects:@"img8.png" , @"img9.png" , ... , nil];
NSArray *images = [toggleValue integerValue] ? imagesA : imagesB;
NSString *name = [images objectAtIndex:rand() % [images count]];
picture.image = [UIImage imageNamed:name];
drawnonward
This is a much better way than using a huge switch statement (or two).
JeremyP