2

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.

2
  • What else is in your array other than "Billy" and "Chris"? Because they are at the top. Commented Oct 7, 2014 at 14:26
  • There are two println() statements. The first confirms that there is data in the array. The second outputs the NSUserDefaults showing that the array wasn't added. Commented Oct 7, 2014 at 17:04

1 Answer 1

2

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] = []
Sign up to request clarification or add additional context in comments.

1 Comment

This is old question but you saved my life. Thank you very much dude :) I did hell of a time research without answer and boom here is answer. You rule! But why it is like that do you know?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.