在下面的代码中,NSUserDefaults 设置是否在我们每次打开应用程序时重置?

In the following code, are the NSUserDefaults settings reset each time we open the app?

我正在慢慢更好地掌握对象范围以及如何在应用程序中传递它们。 Breadcrumbs 示例项目使用 NSUserDefaults 来存储设置。通过查看应用程序委托中的代码和在线文档,我注意到每次方法 willFinishLaunchingWithOptions 运行s 时都会实例化 defaultsDictionary 变量。因此,我假设每次打开示例项目时,如果我们之前更改了设置,我们的设置将被 willFinishLaunchingWithOptions 方法覆盖。我的这个假设是否正确,可以自信地说设置将始终重置为 willFinishLaunchingWithOptions 中提供的默认值?

示例代码如下:

import UIKit
import MapKit // for MKUserTrackingModeNone

@objc(BreadcrumbAppDelegate)
@UIApplicationMain
class BreadcrumbAppDelegate: NSObject, UIApplicationDelegate {

    // The app delegate must implement the window @property
    // from UIApplicationDelegate @protocol to use a main storyboard file.
    var window: UIWindow?

    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        // it is important to registerDefaults as soon as possible,
        // because it can change so much of how your app behaves
        //
        var defaultsDictionary: [String : AnyObject] = [:]

        // by default we track the user location while in the background
        defaultsDictionary[TrackLocationInBackgroundPrefsKey] = true as NSNumber

        // by default we use the best accuracy setting (kCLLocationAccuracyBest)
        defaultsDictionary[LocationTrackingAccuracyPrefsKey] = kCLLocationAccuracyBest as NSNumber

        // by default we play a sound in the background to signify a location change
        defaultsDictionary[PlaySoundOnLocationUpdatePrefsKey] = true as NSNumber

        UserDefaults.standard.register(defaults: defaultsDictionary)

        //print(defaultsDictionary)
        //dump(defaultsDictionary)

        return true
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        //..
        return true
    }

}

我想说我的假设是错误的,但我并没有想到下次用户打开应用程序时会跳过 willFinishLaunchingWithOptions 方法,因此不会重置设置。根据我读过的内容,我假设 willFinishLaunchingWithOptions 方法每次都由 运行 时间环境自动触发。非常感谢任何信息,因为我还在学习。

您的假设不正确。如果没有为给定键保存明确的值,UserDefaults register(defaults:) 只是一种从 UserDefaults 获取值的方法。

最初,UserDefaults 是空的。如果您尝试获取某个键的值,您将返回 nil。如果您显式存储一个键的值,那么获取该键的值当然会为您提供该存储值。

使用 register(defaults:) 只会改变该行为的一部分。如果您尝试读取一个键的值但当前没有值,那么 UserDefaults 将 return 该键的任何注册默认值(如果有),并且 return .如果密钥没有注册默认值,那么您会得到 nil.

register(defaults:) 不重置任何值。它不会替换任何值。它仅在读取 non-existent 值时作为 in-memory 回退存在。