iOSAPP前台后台切换的处理

对于APP前后台切换的监听,大家所熟知的就是,在AppDelegate中实现下面两个方法,能够监听从后台恢复到前台

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    log4info(@"---applicationDidEnterBackground----"); 
   //进入后台  
} 
 
- (void)applicationDidBecomeActive:(UIApplication *)application 
{ 
 
    NSLog(@"---applicationDidBecomeActive----"); 
    //进入前台  
 
     
} 

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    log4info(@"---applicationDidEnterBackground----");
   //进入后台
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{

    NSLog(@"---applicationDidBecomeActive----");
    //进入前台

   
}

但是单个UIViewController怎么监听呢

在-viewDidLoad方法中,添加一下代码监听notification

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(someMethod:) 
                                             name:UIApplicationDidBecomeActiveNotification object:nil]; 

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(someMethod:)
                                             name:UIApplicationDidBecomeActiveNotification object:nil];


别忘了在-dealloc中将监听移除:

[[NSNotificationCenter defaultCenter] removeObserver:self]; 

[[NSNotificationCenter defaultCenter] removeObserver:self];


你可能感兴趣的:(iOS,面试题)