我可以获得一个字符串保存到NSUserDefaults,但我不确定为什么它不能使用下面的代码保存数组。我确信它很小但可以使用指针。
//
// 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())
}
}
结果......
[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]
注意:"姓名:Rob"来自之前的单个字符串save。
答案 0 :(得分:2)
数字......我发布了一个问题,我花了几个小时寻找自己的答案,几分钟后我找到了解决方案。
无论如何,似乎NSUserDefaults不喜欢“String”,但将其改为“NSString”可以。
所以改变是......
var storeNames:[String] = []
到
var storeNames:[NSString] = []