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

标签 ios swift nsuserdefaults

我正在慢慢更好地掌握对象范围以及它们如何在应用程序中传递。 Breadcrumbs 示例项目使用 NSUserDefaults 来存储设置。通过查看应用程序委托(delegate)中的代码和在线文档,我注意到每次运行 willFinishLaunchingWithOptions 方法时都会实例化 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 将返回该键的任何已注册默认值(如果有)并返回它。如果 key 没有注册默认值,那么您将得到 nil

register(defaults:) 不会重置任何值。它不会替换任何值。它仅在读取不存在的值时作为内存中的回退存在。

关于ios - 在下面的代码中,NSUserDefaults 设置是否在我们每次打开应用程序时重置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057893/

相关文章:

ios - 为什么自动布局在 iOS 7 和 iOS 8 中表现不同?

iOS NSUserDefaults 检查 float 键是否存在

ios - 使用 InAppSettingsKit 时读取设置有问题

ios - 使用 cocoapods 时出错 "use_frameworks!"SWIFT

ios - 如何从字符串swift中删除\(反斜杠)

ios - 在 UIView 上调用 setFrame 之后是否必须显式调用 setNeedsDisplay?

swift - 类 'viewController' 没有初始化器并且 'CurrentState' 无法构造,因为它没有可访问的初始化器

swift - 可选展开 SKPhysics 错误

swift - 如何快速制作音频播放器?

ios - 用户默认值在 Swift 3.0 中给出 nil 值