问题描述
当从同一目标下的 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 的这种行为。我可以访问一个键的值,而不能访问其他键的值。
解决方法
Swifts UserDefaults.setValue
外观:
open func setValue(_ value: Any?,forKey key: String)
所以它可以选择任何类型,你应该检查你是否传递了非 nil 值。
首先检查您的可选 defaults
是否不为零,然后验证 data["details"]["equipmentLocationRefreshInterval"].intValue
因为一一存在三个可选:其中两个从您的字典中获取值,最后转换您存储的类型(它是 NSString 吗?)到 Int
和 intValue
并且这些选项中的每一个都可以为零。