refresh data after entering a foreground

前端 未结 2 662
迷失自我
迷失自我 2021-02-04 17:55

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



        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-04 18:49

    You have many problems with your code.

    confusion between Foreground and Background

    - (void)applicationWillEnterForeground:(UIApplication *)application {
        NSLog(@"APPLICATION WILL ENTER BACKGROUND");
        ...
    

    Well, no, it will enter FOREGROUND, and is leaving BACKGROUND.

    missing super call in viewDidLoad

    - (void)viewDidLoad {
        ...
    

    You shall add a [super viewDidLoad];

    direct call to 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.

    unbalanced observers

    - (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).

    missing implementation?

    [[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
            ...
        }
    }
    

提交回复
热议问题