You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS应用首次启动检测:如何仅在首次启动时初始化UserDefaults值

iOS应用首次启动仅初始化一次UserDefaults的方案

系统没有提供专门仅在应用整个生命周期内调用一次的函数,你需要自行判断首次启动状态来实现需求,以下是两种可靠的实现方式:

方法一:直接检查目标Key是否存在

通过判断目标Key是否未被设置过,仅在首次启动时执行初始化:

func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let empIdKey = Constant.shared.empId
    // 仅当Key从未被设置过时,执行初始化
    if UserDefaults.standard.object(forKey: empIdKey) == nil {
        UserDefaults.standard.set(-1, forKey: empIdKey)
    }
    return true
}

说明:只要该Key之前被设置过(哪怕值是-1),object(forKey:)都会返回非nil,因此只会在首次启动时触发初始化。

方法二:使用专门的首次启动标记

通过独立的标记Key判断首次启动,适合需要执行多项初始化操作的场景:

func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let hasLaunchedBeforeKey = "HasLaunchedBefore"
    let empIdKey = Constant.shared.empId
    
    if !UserDefaults.standard.bool(forKey: hasLaunchedBeforeKey) {
        // 首次启动时执行初始化
        UserDefaults.standard.set(-1, forKey: empIdKey)
        // 标记应用已启动过
        UserDefaults.standard.set(true, forKey: hasLaunchedBeforeKey)
        // 可选:确保立即写入磁盘(iOS 12+ 非必须)
        UserDefaults.standard.synchronize()
    }
    return true
}

说明:独立标记的方式不受后续业务逻辑修改目标Key值的影响,可靠性更强。

内容的提问来源于stack exchange,提问作者S. S. Saruar Jahan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 13:20:01