0

Userdefaults value set in swift module returns nil when accessed from Objecive-c files under the same target.

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

When accessed from objective-C classes

[[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.

I am failing to understand this behavior of Userdefaults. I am able to access one key's value and not others.

Akaanksha
  • 161
  • 1
  • 14

1 Answers1

0

Swifts UserDefaults.setValue looks:

open func setValue(_ value: Any?, forKey key: String)

So it can get optional of any type and you should check that you pass not nil value.

First check that your optional defaults is not nil and then verify data["details"]["equipmentLocationRefreshInterval"].intValue because there are three optionals one by one: two of them to get a value from your dictionary and last to convert your stored type (is it NSString?) to Int with intValue and each of these optionals can be nil.

iUrii
  • 11,742
  • 1
  • 33
  • 48