سؤال

In my app I have pretty long

- (void)appDidEnterBackground:(NSNotification*)notif method,

it takes 1-2 seconds to execute. This causes the following issue: if I close app and open it again very fast, than

- (void)appWillEnterForeground:(NSNotification*)notif

is being called before -appDidEnterBackground is finished, which leads to crash - data is not consistent, or something like this. Rather than investigate what exactly is wrong in my data, I want to prevent this case from ever happening - I want to wait until appDidEnterBackground is done.

My code:

- (void)appDidEnterBackground:(NSNotification*)notif
{
    [self processAppDidEnterBackgroundRoutines];

    NSLog(@"%s - end", __FUNCTION__);
}

- (void)processAppDidEnterBackgroundRoutines
{
    // 1-2 seconds prosessing
}

- (void)appWillEnterForeground:(NSNotification*)notif
{   
    NSLog(@"%s - begin", __FUNCTION__);
}

I tried to call

[self performSelectorOnMainThread:@selector(processAppDidEnterBackgroundRoutines) withObject:nil waitUntilDone:YES];

, but it doesn't help for some reason - appWillEnterForeground: is still being called before processAppDidEnterBackgroundRoutines is finished.

Does anyone have others ideas how to synchronise this calls?

هل كانت مفيدة؟

المحلول

Would it work for you to put both in a serial queue?

- (void)appDidEnterBackground:(NSNotification*)notif
{
    dispatch_sync( serialQueue, ^()
    {
        [self processAppDidEnterBackgroundRoutines];
    });
}

- (void)processAppDidEnterBackgroundRoutines
{
    // 1-2 seconds prosessing
}

- (void)appWillEnterForeground:(NSNotification*)notif
{   
    dispatch_sync(serialQueue, ^()
    {
       // do your stuff
    });
}

نصائح أخرى

Your problem appears to be because you're using performSelectorOnMainThread: in your appDidEnterBackground: method. This is causing that selector to be run later on, because you're already running on the main thread. Just stop doing performSelectorOnMainThread:, because it's unnecessary, and is what's causing your problem.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top