iOS app applicationWillEnterForeground and it stuc

2019-04-06 01:59发布

问题:

I add this function to post a notification when the app enter foreground:

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName: @"UIApplicationWillEnterForegroundNotification" object: nil];
}

In my own class:

- (void) handleEnterForeground: (NSNotification*) sender
{
    [self reloadTableData];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(handleEnterForeground:)
                                             name: @"UIApplicationWillEnterForegroundNotification"
                                           object: nil];
}

but the handleEnterForeground: function will called twice, I don't know why. The reloadTableData: function will call remote webService , so when the app enter foreground, it will stuck for a while.

回答1:

The system will call that event automatically. The reason it fires twice is because you manually fire it again.

P.S. It's better to use the variable name UIApplicationWillEnterForeground, instead of a NSString literal.

EDIT: I realize now the confusion is coming from the fact that you didn't know that this even name was already taken. As a note to other people who run into this kind of problem, it is a good practice to prefix your event names with your project prefix (i.e. XYZEventNotification) to avoid collisions.