iOS app applicationWillEnterForeground and it stuck for a while

jxdwinter picture jxdwinter · May 18, 2012 · Viewed 8.4k times · Source

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.

Answer

borrrden picture borrrden · May 18, 2012

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.