我有一个结构,有时,对于某些用户,在尝试访问该类型的变量时会出现崩溃.
struct AppSettings { var mute:Bool { didSet { if mute != oldValue { let savedSettings = NSUserDefaults.standardUserDefaults() savedSettings.setBool(mute,forKey: KEY_SETTING_MUTE) } } } init() { let savedSettings = NSUserDefaults.standardUserDefaults() if let savedMute = savedSettings.objectForKey(KEY_SETTING_MUTE) as? Bool { mute = savedMute } else { mute = false } } } var appSettings = AppSettings()
在应用程序启动期间的某个地方,它有时会崩溃
if appSettings.mute { // This will sometimes cause a crash } // in AppDelegate or the methods it calls
这仅适用于某些用户,我似乎无法重现它.不是重现它是最糟糕的,因为它让我没有任何工作.
我更改了代码的某些部分并执行它.一切都很好,没有崩溃.
struct AppSettings { var mute:Bool { didSet { if mute != oldValue { let savedSettings = UserDefaults.standard savedSettings.set(mute,forKey: "MUTE") } } } init() { let savedSettings = UserDefaults.standard if let savedMute = savedSettings.object(forKey: "MUTE") as? Bool { mute = savedMute } else { mute = false } } } override func viewDidLoad() { super.viewDidLoad() var appSettings = AppSettings() if appSettings.mute { print("It is mute ...") } }