ios - 当从同一目标下的目标 c 文件访问时,在 Swift 文件中设置的用户默认值返回 nil
问题描述
当从同一目标下的 Objecive-c 文件访问时,在 swift 模块中设置的 Userdefaults 值返回 nil。
defaults?.setValue(data["details"]["equipmentLocationRefreshInterval"].intValue, forKey: "equipmentLocationRefreshInterval")
defaults?.setValue(data["details"]["hasEquipmentDeviceLocationConfigured"].boolValue, forKey: "hasEquipmentDeviceLocationConfigured")
defaults?.synchronize()
//data["details"]["equipmentLocationRefreshInterval"] = 30
//data["details"]["hasEquipmentDeviceLocationConfigured"] = TRUE
从 Objective-C 类访问时
[[NSUserDefaults standardUserDefaults] valueForKey:@"equipmentLocationRefreshInterval"];
//returns nil
[[NSUserDefaults standardUserDefaults] integerForKey:@"equipmentLocationRefreshInterval"];
//returns <nil>
[[NSUserDefaults standardUserDefaults] boolForKey:@"hasEquipmentDeviceLocationConfigured"];
// returns true when set as true in swift module.
我无法理解 Userdefaults 的这种行为。我能够访问一个键的值,而不是其他的。
解决方案
斯威夫特UserDefaults.setValue
看起来:
open func setValue(_ value: Any?, forKey key: String)
所以它可以得到任何类型的可选,你应该检查你传递的不是 nil 值。
首先检查您的可选项defaults
是否不为零,然后验证是否data["details"]["equipmentLocationRefreshInterval"].intValue
存在三个可选项:其中两个用于从字典中获取值,最后将您的存储类型(是 NSString 吗?)转换为Int
withintValue
和这些选项中的每一个可以为零。