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. :)
synchronize
should only be used to "force" syncing. This can be useful for example when debugging and there's a chance of crashing, etc. – Affaire