Christopher Wade Cantley
Christopher Wade Cantley

Reputation: 7232

nsuserdefault not saving array - Swift

I can get a single string to save to NSUserDefaults but I am not sure why it won't save an array using the below code. I am sure it is something small but could use a pointer.

//
//  ViewController.swift
//  DemoUserDefaults
//
//  Created by Chris Cantley on 10/7/14.
//  Copyright (c) 2014 Chris Cantley. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

var storeNames:[String] = []

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    storeNames.append("Billy")
    storeNames.append("Chris")

    // Shows the strings in the array.
    println(storeNames)


    // puts mutable into immutable object
    let holdNames = storeNames

    // "should" store the object into UserDefaults... but does not.
    NSUserDefaults.standardUserDefaults().setObject(holdNames, forKey: "storeNames")
    NSUserDefaults.standardUserDefaults().synchronize()


    // Displays all data in UserDefaults... array is missing.
    println(NSUserDefaults.standardUserDefaults().dictionaryRepresentation())


}

}

The Result...

[Billy, Chris]
[NSLanguages: (
en
), AppleITunesStoreItemKinds: (
audiobook,
"tv-episode",
booklet,
software,
"software-update",
"itunes-u",
ringtone,
"tv-season",
movie,
mix,
newsstand,
song,
wemix,
tone,
artist,
"podcast-episode",
podcast,
document,
eBook,
album,
"music-video"
), AppleKeyboardsExpanded: 1, NSInterfaceStyle: macintosh, AppleKeyboards: (
"en_US@hw=US;sw=QWERTY",
"emoji@sw=Emoji",
"en_US@hw=US;sw=QWERTY"
), AppleLanguages: (
en
), names: Rob]

Note : "names:Rob" is from a previous single string save.

Upvotes: 2

Views: 1135

Answers (1)

Christopher Wade Cantley
Christopher Wade Cantley

Reputation: 7232

Figures... I post a question I have spend hours looking to answer on my own, and minutes later I find the solution.

Anyways, it would seem that NSUserDefaults doesn't like "String" however changing it to "NSString" works.

So the change is...

var storeNames:[String] = []

to

var storeNames:[NSString] = []

Upvotes: 2

Related Questions