Search code examples
swiftdictionarynsuserdefaultsnsnumber

NSNumber swift Dictionary to userdefaults swift3


I am trying to save swift dictionary [NSNumber : NSNumber] to UserDefaults. I have already tried to cast it as NSDictinonary, but still, the application crashes when I use set() function.

Key is a beacon minor key (NSNumber) Value is an NSTimeinterval cast as NSNumber

the crash:

libc++abi.dylib: terminating with uncaught exception of type NSException

var  recentBeacons: [NSNumber : NSNumber] = [:]

func saveRecentBeaconDict()
{
    let recentBeaconKeys = recentBeacons.keys
    print("keys type is \(String(describing: recentBeaconKeys.self))")

    let recentBeaconsNSDict = recentBeacons as NSDictionary
    UserDefaults.standard.set(recentBeaconsNSDict, forKey:"recentBeacons")
}

prints out: keys type is LazyMapCollection< Dictionary < NSNumber, NSNumber >, NSNumber >(_base: [46171: 1501585588.173543], _transform: (Function))


Solution

  • Try with below answer.

        var  recentBeacons: [NSNumber : NSNumber] = [:]
        func saveRecentBeaconDict()
        {
            let archivedObject = NSKeyedArchiver.archivedData(withRootObject: recentBeacons as NSDictionary)
            UserDefaults.standard.set(archivedObject, forKey: "recentBeacons")
    
            let data = UserDefaults.standard.object(forKey: "recentBeacons") as? Data
            if let _data = data {
    
                let allData = NSKeyedUnarchiver.unarchiveObject(with: _data) as! NSDictionary
                print(allData)
            }
        }