我有一个视图控制器,它使用NSTimer来执行一些代码.

检测应用程序何时转到后台以便我可以暂停计时器的最佳方式是什么?

推荐答案

你可以让任何感兴趣的类在应用程序进入后台时接收通知.这是将这些类与AppDelegate耦合的一个很好的替代方法.

初始化所述类时:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];

回应通知

-(void)appWillResignActive:(NSNotification*)note
{

}
-(void)appWillTerminate:(NSNotification*)note
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];

}

Ios相关问答推荐

自定义alert 未执行任何操作

RFID scanner 的蓝牙服务 UUID?

如何在Combine发布者之间强制执行最小延迟

垂直分页 UIScrollView 高度不正确

DllImport with .a file for iOS in MAUI

使用 AVCaptureDeviceTypeBuiltInTripleCamera 时 Select 合适的相机进行条码扫描

expo EAS build (iOS) 在 Pod 安装步骤中失败 (SDK45 & 46)

FileHandle 不会在 iOS 中释放内存

SwiftUI - ScrollView 不显示底部文本

.overlay 和 body 是什么 swift 概念

DateFormatter 使用 TimeZone 和 Locale 的特定组合返回 nil

async/await、Task 和 [weak self]

为什么我的应用在 Testflight 中没有下载 dSYM 按钮?

如何使用情节提要重新排列 UITabBarController 项目?

iOS 10 错误:UICollectionView 接收到具有不存在索引路径的单元格的布局属性

无论我将构建版本或应用程序版本更改为什么,都会出现 ITEMS-4238冗余二进制上传错误

判断可选数组是否为空

水平滚动 UICollectionView 时对齐单元格的中心

UIGestureRecognizer 阻止子视图处理touch 事件

为什么我需要@1x、@2x 和@3x iOS 图像?