Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad form to synchronize NSUserDefaults in -(void)dealloc?

I load from NSUserDefaults in my object's init method. Can I save to NSUserDefaults in my object's dealloc method?

Something exactly like:

-(void)dealloc {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:self.filenamesArray forKey:self.defaultsKey];
    [userDefaults synchronize];
    self.filenamesArray = nil;
    self.defaultsKey = nil;
    [super dealloc];
}

good, bad, ok? if it's not good, where would be better.

Edit:

Thanks for the detailed responses. All those things make sense. Another reason I discovered why this is a bad place to save to user defaults, is that dealloc is only called when an object deallocates nicely. If my app is killed, this code never runs. Similarly, if the app is pushed into the background (iOS 4) this doesn't run. I've also removed the explicit [userDefaults synchronize] call. It makes me a little nervous, but I put my trust in apple on this one. :)

like image 525
Kenny Winker Avatar asked Nov 13 '10 22:11

Kenny Winker


1 Answers

It's bad because by the time -dealloc is called, other objects have given up interest in it. This can have lots of different implications.

The better place to set user defaults is the very moment a setting changes. That way it's persisted right away and the app can be killed with no worries about a setting not being persisted because parts of your object graph might already have gone away.

like image 124
Joshua Nozzi Avatar answered Oct 21 '22 14:10

Joshua Nozzi