杀死应用程序时有两个UIApplicationDidEnterBackgroundNotification

时间:2014-09-15 20:13:29

标签: ios observers

iOS模拟器7.1中的

,下面是简单的代码:

  1. 命令+ shift + H模拟按下主页按钮,输出逻辑上:
    • activing
    • 辞职
    • backgrounding
  2. 双命令+ shift + H模拟双击主页按钮然后轻扫以杀死应用程序,输出“奇怪”:
    • activing
    • 辞职
    • backgrounding
    • backgrounding
  3. 在案例2中出于哪种原因,后台被调用两次?请注意,使用iOS 8.0案例2.显示:      - 活动      - 辞职      - 背景

    #import "ViewController.h"
    
    @interface ViewController ()
    @end
    
    @implementation ViewController {}
    
    - (void)backgrounding {
        NSLog(@"backgrounding");
    }
    
    - (void)resigning {
        NSLog(@"resigning");
    }
    
    - (void)activing {
        NSLog(@"activing");
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backgrounding) name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resigning) name:UIApplicationWillResignActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activing) name:UIApplicationDidBecomeActiveNotification object:nil];
    }
    
    @end
    

1 个答案:

答案 0 :(得分:0)

iOS 7(至少在模拟器中)发送两个后台事件。您只需编写应用程序即可优雅地处理多个后台事件。

我通过创建一个自定义UIApplication子类来检查这一点,该子类记录每个事件,以及其内部GraphicsServices事件(如果有):

#import "MyApplication.h"

@interface NSObject (hack)

- (id)_gsEvent;

@end

@implementation MyApplication

- (void)sendEvent:(UIEvent *)event {
    NSLog(@"event=%@", event);
    if ([event respondsToSelector:@selector(_gsEvent)]) {
        NSLog(@"_gsEvent=%@", event._gsEvent);
    }
    [super sendEvent:event];
}

@end

这是在多任务处理屏幕中刷掉应用程序时的输出:

2014-09-15 16:14:32.894 background[19438:70b] event=<UIInternalEvent: 0x8c148e0>
2014-09-15 16:14:32.894 background[19438:70b] _gsEvent=<GSEvent 0xd9149f0>{type = 32, windowLoc = (0.000000, 0.000000)}
2014-09-15 16:14:32.895 background[19438:70b] event=<UIInternalEvent: 0x8c148e0>
2014-09-15 16:14:32.895 background[19438:70b] _gsEvent=<GSEvent 0x8f1ac20>{type = 7d7, windowLoc = (0.000000, 0.000000)}
2014-09-15 16:14:32.896 background[19438:70b] backgrounding
2014-09-15 16:14:32.943 background[19438:70b] event=<UIInternalEvent: 0x8c148e0>
2014-09-15 16:14:32.944 background[19438:70b] _gsEvent=<GSEvent 0x8b22c90>{type = 7d7, windowLoc = (0.000000, 0.000000)}
2014-09-15 16:14:32.944 background[19438:70b] backgrounding

您可以看到有两个独立的GraphicsServices事件(具有不同的地址),每个UIApplicationDidEnterBackgroundNotification一个。