9

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
jxdwinter
  • 2,339
  • 6
  • 36
  • 56

1 Answers1

17

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.

borrrden
  • 33,256
  • 8
  • 74
  • 109
  • 1
    Im so sure I called that function once. – jxdwinter May 18 '12 at 07:46
  • 1
    @cnu *he* is firing it once, and iOS runtime is firing it once. This event gets called automatically. – borrrden May 18 '12 at 08:22
  • Thank you , it's OK now!!! I change "UIApplicationWillEnterForegroundNotification" to an other word . – jxdwinter May 18 '12 at 08:31
  • 2
    Instead of changing it to another word...why not just take out that code, and use the event that comes automatically? – borrrden May 18 '12 at 08:48
  • His name is borrrden, not OLO. – Jonny Sep 09 '16 at 08:30
  • I have the same issue, no double registration with the samen name, 100% sure. The only solution is to post notification with a unique name in AppDelegate's applicationWillEnterForeground or applicationDidBecomeActive. – AndaluZ Feb 20 '20 at 10:31
  • "After calling this method, the app also posts a UIApplicationDidBecomeActiveNotification notification to give interested objects a chance to respond to the transition." according to Apple. Well I get 2 notifications after each other. – AndaluZ Feb 20 '20 at 10:32