Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Int64 in UserDefaults

I define my dictionary like this:

var teamsData = Dictionary<String,Dictionary<String,Int64>>()

Then, I am trying to store it in userdefaults:

NSUserDefaults.standardUserDefaults().setObject(teamsData, forKey: "teamsData")

but it throws the error:

Type Dictionary<String,Dictionary<String,Int64>> does not conform to protocol 'Any Object'
like image 680
Kashif Avatar asked Jan 27 '15 18:01

Kashif


People also ask

What can be stored in UserDefaults?

You can use UserDefaults to store any basic data type for as long as the app is installed. You can write basic types such as Bool , Float , Double , Int , String , or URL , but you can also write more complex types such as arrays, dictionaries and Date – and even Data values.

How much data can you store in UserDefaults?

Currently, there is only a size limit for data stored to local user defaults on tvOS, which posts a warning notification when user defaults storage reaches 512kB in size, and terminates apps when user defaults storage reaches 1MB in size. For ubiquitous defaults, the limit depends on the logged in iCloud user.

How data is stored in UserDefaults?

Updating the Prospects initializer so that it loads its data from UserDefaults where possible. Adding a save() method to the same class, writing the current data to UserDefaults . Calling save() when adding a prospect or toggling its isContacted property.

Is UserDefaults thread safe?

Thread SafetyThe UserDefaults class is thread-safe.


1 Answers

A user default object can only be an instance (or a combination of instances) of NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.

Some Swift types are automatically bridged to Foundation types, e.g. Int, UInt, Float, Double and Bool are bridged to NSNumber. So this could be saved in the user defaults:

var teamsData = Dictionary<String,Dictionary<String,Int>>()

On 64-bit architectures, Int is a 64-bit integer, but on 32-bit architectures, Int is a 32-bit integer.

The fixed-sized integer types such as Int64 are not automatically bridged to NSNumber. This was also observed in Swift - Cast Int64 to AnyObject for NSMutableArray. Therefore, to store 64-bit integers in the user defaults you have to use NSNumber explicitly:

var teamsData = Dictionary<String,Dictionary<String,NSNumber>>()

// Example how to add a 64-bit value:
let value : UInt64 = 123
teamsData["foo"] = ["bar" : NSNumber(unsignedLongLong: value)]
like image 92
Martin R Avatar answered Oct 13 '22 20:10

Martin R