After changing the default settings, I would like to refresh data of myViewController when I enter the foreground in AppDelegate. What I do is
AppDelegate.m
You have many problems with your code.
- (void)applicationWillEnterForeground:(UIApplication *)application {
NSLog(@"APPLICATION WILL ENTER BACKGROUND");
...
Well, no, it will enter FOREGROUND, and is leaving BACKGROUND.
- (void)viewDidLoad {
...
You shall add a [super viewDidLoad];
- (void)applicationWillEnterForeground:(UIApplication *)application {
[myViewController viewDidLoad];
...
Well, no, do not call viewDidLoad
yourself, as it is supposed to only be called once by the system. Super classes or sub classes may be incompatible with multiple calls.
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSettings:) name:UIApplicationDidFinishLaunchingNotification object:nil];
...
By calling viewDidLoad multiple times, you were actually registering multiple observers for the same event. You need to have in your code a symmetry with as many calls to removeObserver
than addObserver
(note that you can also remove multiple observers at the same time).
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(defaultsChanged:)
name:NSUserDefaultsDidChangeNotification
object:nil];
Well, we don't see your implementation of defaultsChanged:
, so it's unclear what you were trying to achieve. Was it to set a BOOL to YES and subsequently check that value to determine if preferences were changed? Something like that?
- (void)defaultsChanged:(id)notif {
self.refreshData = YES;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
if (self.refreshData) {
self.refreshData = NO;
// we refresh data now
...
}
}