且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Swift / iOS中从UITableView删除行并从NSUserDefaults更新数组的正确方法

更新时间:2023-12-04 17:27:47

基本上是正确的,但是如果删除了某些内容,则只应保存用户默认设置。

Basically it's correct, but you should only save in user defaults if something has been deleted.

if editingStyle == UITableViewCellEditingStyle.Delete {
    array.removeAtIndex(indexPath.row)
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
    let userDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setObject(array, forKey: "myArrayKey")
}

不需要也不建议读回数组。

Reading the array back is not needed and not recommended.

cellForRowAtIndexPath 重用该单元格,您需要在Interface Builder中指定标识符。

In cellForRowAtIndexPath reuse the cell, you need to specify the identifier in Interface Builder.

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) 

数据源数组必须在上声明

The data source array must be declared on the top level of the class

var array = [String]()

然后在 viewDidLoad 中分配值并重新加载表视图。

then assign the value in viewDidLoad and reload the table view.

override func viewDidLoad() {
    super.viewDidLoad()

    let userDefaults = NSUserDefaults.standardUserDefaults()
    guard let data = userDefaults.objectForKey("myArrayKey") as? [String] else {
        return 
    }
    array = data
    tableView.reloadData()
}