Best way to reset app settings in iOS4 with fast app switching
I made a settings panel for my app with a slider that you can set to "Erase preferences on next launch" (inside the main iPhone settings app). In my app's delegate, I made it so that applicationWillEnterForeground would check if the setting switch was set in the preferences and clear my settings with:
[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSB开发者_开发百科undle mainBundle] bundleIdentifier]];
if necessary.
My question is: If viewDidLoad and viewDidAppear in my view controller don't run after I make the settings change due to iOS 4's fast app switching (the view is still loaded when I come back from the settings app), how can I alert these view controllers that the settings were reset so they can re-load all of their data? If only there was a way to call [MainViewController initData] from the delegate but sadly that can't be done. It seems like unless there is an action that happens in the view controller, there is no way for it to know to check if the settings had been reset.
Any help would be much appreciated.
Notifications are often the best way to communicate across controllers and such.
First, separate the initialization code into a method in your view controller that's called by your viewDidLoad
/viewWillAppear
. For the sake of reference we'll call it resetUser.
Next, create a notification that fires from applicationWillEnterForeground
when it sees that this switch has been thrown. Let's call it userRequestsReset.
[[NSNotificationCenter defaultCenter] postNotificationName:@"userRequestsReset"
object:nil];
Finally, in your viewController listen for the userRequestsReset notification and call the resetUser method when the notification is received.
In your viewController's viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(resetNoticeReceived:)
name:@"userRequestsReset"
object:nil];
The method in your viewController that responds to the notification:
- (void) resetNoticeReceived:(NSNotification *)notif {
[self resetUser];
}
And removing the viewController as an observer in viewDidUnload:
[[NSNotificationCenter defaultCenter] removeObserver:self];
精彩评论