Storing a dictionary of Int and Array in NSUserDef

2019-06-09 15:37发布

问题:

What I know so far about the subject:

I understand that there are only certain data types that you can store into NSUserDefaults:

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData.

And I know I can do the following:

var cities = [String]()
cities = NSUserDefaults.standardUserDefaults().objectForKey("cities") as! NSArray

And this is permissible because it casts my cities String array into an NSArray and NSUserDefaults accepts this data type. However, I have a dictionary of an Int and an Array, namely, var addressDict = Dictionary<Int, Array<String>>(). I know that NSUserDefaults accepts NSDictionary, NSInteger, and NSArray.

What I want to know how to do:

I want to cast my addressDict properly so that NSUserDefaults accepts my addressDict. Though, I know that the Dictionary, Array, and Int can be casted into it's NS counterparts as separate entities, but I don't know how to do that altogether as the data type Dictionary<Int, Array<String>>(). Any help? For example, I know this is completely wrong but something like NSDictionary<NSInteger, NSArray<String>> or something.

回答1:

To store a dictionary in NSUserDefaults you need to convert them to NSData first. NSKeyedArchiver and NSKeyedUnarchiver are perfect for the job. The following example shows how to store your dictionary in NSUserDefaults and read it back.

    var addressDict = Dictionary<Int, Array<String>>()
    addressDict[3] = ["string1", "string2"] //some example values
    let data = NSKeyedArchiver.archivedDataWithRootObject(addressDict) //archiving
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(data, forKey: "address") //storing
    if let data2 = defaults.objectForKey("address") as? NSData { //reading
        let addressDict2 = NSKeyedUnarchiver.unarchiveObjectWithData(data2) //unarchiving
        print(addressDict2)
    }