Search code examples
objective-cioscocoa-touchnslogviewdidload

viewDidLoad not running when expected


I have the following code in my viewDidLoad to change an image:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    if ([defaults objectForKey:@"colour"] == nil) {
        [defaults setObject:@"Red" forKey:@"colour"];
        [defaults setInteger:0 forKey:@"colourIndex"];
        [defaults synchronize];
    }


    [background setImage:[UIImage imageNamed:[defaults objectForKey:@"colour"]]];
    NSLog(@"%@", [defaults objectForKey:@"colour"]);
    // Logs "Blue"
}

When I open my flipside view in the iPhone Simulator and then go back to my original view, the result of the NSLog doesn't change and the image doesn't change. Why is this happening?


Solution

  • Move this code to viewWillAppear. viewDidLoad is not called every time the view is presented.

    This link provides a good explanation.

    UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?