NSUserDefaults用于在UITableView中存储和检索数组

时间:2015-12-24 10:36:56

标签: ios swift uitableview nsuserdefaults

我想通过NSUserDefaults每次在数组中存储字符串。我想在UITableView cell

中检索那些字符串(字符串集)

我的代码

enum defaultsKeys {
    static let keymodel = "firstStringKey"
    static let keyVersion = "secondStringKey"
    static let keyBodystyle = "thirdStringKey"
    static let keyTotalprice = "fourthStringKey"
    static let keyDate = "fifthStringKey"

}

override func viewDidLoad() {
    super.viewDidLoad()

    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setValue(mymodel, forKey: defaultsKeys.keymodel)
    defaults.setValue(myversion, forKey: defaultsKeys.keyVersion)
    defaults.setValue(mybodystyle, forKey: defaultsKeys.keyBodystyle)
    defaults.setValue(mytotalprice, forKey: defaultsKeys.keyTotalprice)
    defaults.setValue(mymodel, forKey: defaultsKeys.keyDate)

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell:selectedcarcell = tableView.dequeueReusableCellWithIdentifier("selectedcarcell") as! selectedcarcell


    let defaults = NSUserDefaults.standardUserDefaults()

    if let stringmodel = defaults.stringForKey(defaultsKeys.keymodel) {
        cell.carname.text = stringmodel
    }

    if let stringversion = defaults.stringForKey(defaultsKeys.keyVersion) {
        cell.carversion.text = stringversion
    }

    if let stringbodystyle = defaults.stringForKey(defaultsKeys.keyBodystyle) {
        cell.carbodystyle.text = stringbodystyle
    }

    if let stringfinalprice = defaults.stringForKey(defaultsKeys.keyTotalprice) {
       cell.finalprice.text = stringfinalprice
    }

    if let stringdate = defaults.stringForKey(defaultsKeys.keyDate) {
        cell.date.text = stringdate
    }

    return cell

}

我正在为字符串做这个,但我想为数组做这个,所以我该怎么做呢

这是我的输出 enter image description here

但是当我第二次插入nother值时,我之前的值不会出现在数组中。那么我怎么能这样做呢?我也想要以前所有的价值?

1 个答案:

答案 0 :(得分:2)

通过一些研究你会发现,它的工作方式非常相似:

保存数组:

let defaults = NSUserDefaults.standardUserDefaults()
let array = ["1", "2"]
defaults.setObject(array, forKey: "array")

检索数组:

let array = defaults.objectForKey("array")
print(array)


如果您想在每次运行应用程序时向数组添加内容,请使用以下内容:

var array = NSUserDefaults.standardUserDefaults().objectForKey("Array") as? [AnyObject]
if array == nil { // This will only happen the first time the user opens the app
    array = [AnyObject]()
}
array!.append("someobject")
NSUserDefaults.standardUserDefaults().setObject(array, forKey: "Array")

如果您将 cellForRowAtIndexPath 更改为如下所示,则可以在UITableViewCell中显示每个元素:

cell.carname.text = array[indexPath.row]