0

I have a NSUserDefault dictionary. One of the keys has a value of type [Int]. I'm looking to figure out how to append Ints to that embedded array.

var dictionary = ["keyOne" : [1,2,3,4,5]]
defaults.setObject(dictionary, forKey: "defaultDictionary")

What I'm currently doing is saving the dictionary to a variable, creating a variable array from the new dictionary variable and then appending that. Then I'm updating the dictionary with the new array and saving that dictionary back to the defaults.

Does anyone out there know of a direct way to append to the array without having to do all the middle work?

Ajean
  • 5,528
  • 14
  • 46
  • 69

3 Answers3

1

You can create a computed property and define getter/setter to save it automatically to user defaults. You will need to cast from [String:[Int]] to [String:AnyObject] to be able to save it to NSUSerDefaults:

var defaultDictionary:[String:[Int]] {
    get {
        return NSUserDefaults().dictionaryForKey("defaultDictionary") as? [String:[Int]] ??  [:]
    }
    set {
        NSUserDefaults().setObject(newValue as [String:AnyObject], forKey: "defaultDictionary")
    }
}


print(defaultDictionary["keyOne"]?.description ?? "")  // [1, 2, 3, 4, 5]
print(defaultDictionary["keyTwo"]?.description ?? "")  // [1, 2, 3]

defaultDictionary["keyOne"]?.append(6)
defaultDictionary["keyTwo"]?.append(4)

print(defaultDictionary["keyOne"]?.description ?? "")  // [1, 2, 3, 4, 5, 6]
print(defaultDictionary["keyTwo"]?.description ?? "")  // [1, 2, 3, 4]
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
0

You can only read and write objects from NSUserDefaults. If you use it often write some methods e.g:

func updateDefaultsWithArray(array: [Int]) {
    let dictionary = ["keyOne" : array]
    let defaults = NSUserDefaults()
    defaults.setObject(dictionary, forKey: "defaultDictionary")
}
zuziaka
  • 575
  • 3
  • 10
0

You can do it like this:

func saveArray(valueArray: [AnyObject], key: String) {
    let dataToSave = NSKeyedArchiver.archivedDataWithRootObject(valueArray)
    NSUserDefaults.standardUserDefaults().setObject(dataToSave, forKey: key)
}
Alexey Pichukov
  • 3,377
  • 2
  • 19
  • 22