且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iphone 4 sdk:检测从后台模式返回

更新时间:2023-02-16 19:07:10

以下是监听此类事件的方法:

Here's how to listen for such events:

// Register for notification when the app shuts down
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillTerminateNotification object:nil];

// On iOS 4.0+ only, listen for background notification
if(&UIApplicationDidEnterBackgroundNotification != nil)
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationDidEnterBackgroundNotification object:nil];
}

// On iOS 4.0+ only, listen for foreground notification
if(&UIApplicationWillEnterForegroundNotification != nil)
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillEnterForegroundNotification object:nil];
}

注意:if(&SomeSymbol) 检查确保您的代码可以在 iOS 4.0+ 和 iOS 3.x 上运行 - 如果您针对 iOS 4.x 或 5 构建.x SDK 并将部署目标设置为 iOS 3.x 您的应用仍然可以在 3.x 设备上运行,但相关符号的地址将为 nil,因此它不会尝试请求在 3 上不存在的通知.x 设备(这会使应用程序崩溃).

Note: The if(&SomeSymbol) checks ensure that your code will work on iOS 4.0+ and also on iOS 3.x - if you build against an iOS 4.x or 5.x SDK and set the deployment target to iOS 3.x your app can still run on 3.x devices but the address of relevant symbols will be nil, and therefore it won't try to ask for notifications that don't exist on 3.x devices (which would crash the app).

更新:在这种情况下,if(&Symbol) 检查现在是多余的(除非您真的需要支持 iOS 3由于某些原因).但是,了解这种技术有助于在使用 API 之前检查它是否存在.我更喜欢这种技术而不是测试操作系统版本,因为您正在检查特定 API 是否存在,而不是使用外部知识来了解哪些 API 存在于哪些操作系统版本中.

Update: In this case, the if(&Symbol) checks are now redundant (unless you really need to support iOS 3 for some reason). However, it's useful to know this technique for checking if an API exists before using it. I prefer this technique than testing the OS version because you are checking if the specific API is present rather than using outside knowledge of what APIs are present in what OS versions.