Search code examples
objective-cios5viewdidloaddidreceivememorywarning

iPhone : Memory warning destroying strong objects?


I am developing an app with a view to take pictures.

I faced a very strange behavior lately, here is my code.

@interface ViewControllerPhotos : UIViewController 
@property (strong) NSString* _albumID;
@end

@implementation ViewControllerPhotos
@synthesize _albumID;

- (void)didReceiveMemoryWarning
{
   return;
   // commented or not : give the same issue
   //    [super didReceiveMemoryWarning];
   // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationItem setHidesBackButton:YES];

    self._albumID = [Tools generateUUID];

    NSLog(@"new photoset : local UUID \"%@\"", self._photoSetLocalID);
}

@end

My issue is : if there is a memory warning, the UID stored in _albumID is forgotten and regenerated so my album is broken in two. Why ? Should not the strong keyword be able to keep the current value ?

Or is it because the viewDidload is called again ? If it's the case then how to be sure we load our view for the first time for a proper init ? The methods sounded to be designed for it.


Solution

  • Well, you could figure this out with the debugger and the manual, but...

    viewDidLoad is called when the view loads. In a low memory situation when the viewcontroller is not visible, the view may be unloaded. There's a viewDidUnload method in iOS3+. Then when you press the back button and the view becomes visible again, viewDidLoad would be called again as you suspected.

    The way around this is either to store the UUID so when its reloaded it's not re-generated.

    Or, you could put the assignment in the init method. That way it's only ever called once.