【问题标题】:The proper way to delete rows from UITableView and update array from NSUserDefaults in Swift / iOS在 Swift / iOS 中从 UITableView 删除行并从 NSUserDefaults 更新数组的正确方法
【发布时间】:2017-01-30 05:21:33
【问题描述】:

UITableView 删除行并从 NSUserDefaults 更新数组的正确方法是什么?

在下面的示例中,我正在从 NSUserDefaults 读取一个数组并提供一个 UITableView 及其内容,我还允许用户删除 UITableView 中的项目我不确定是什么时候读取和写入NSUserDefaults,以便在删除行后立即更新表。如您所见,我首先在viewDidLoad 方法中读取数组,然后在commitEditingStyle 方法中重新保存它。使用这种方法,当删除一行时,我的表不会重新加载。

override func viewDidLoad() {
    super.viewDidLoad()
     // Lets assume that an array already exists in NSUserdefaults.
     // Reading and filling array with content from NSUserDefaults.
    let userDefaults = NSUserDefaults.standardUserDefaults()
    var array:Array = userDefaults.objectForKey("myArrayKey") as? [String] ?? [String]()
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel!.text = array[indexPath.row]
    return cell
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        array.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }
  // Save array to update NSUserDefaults     
 let userDefaults = NSUserDefaults.standardUserDefaults()
 userDefaults.setObject(array, forKey: "myArrayKey")


 // Should I read from NSUserDefaults here right after saving and then reloadData()?
 }

这通常是如何处理的?

谢谢

【问题讨论】:

    标签: ios arrays swift uitableview nsuserdefaults


    【解决方案1】:

    基本上是正确的,但只有在删除某些内容时才应保存在用户默认值中。

    if editingStyle == .delete {
        array.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)
        let userDefaults = UserDefaults.standard
        userDefaults.set(array, forKey: "myArrayKey")
    }
      
    

    不需要也不推荐回读数组。

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

    let cell = tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) 
    

    数据源数组必须声明在类的顶层

    var array = [String]()
    

    然后在viewDidLoad 中赋值并重新加载表格视图。

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let userDefaults = UserDefaults.standard
        guard let data = userDefaults.array(forKey: "myArrayKey") as? [String] else {
            return 
        }
        array = data
        tableView.reloadData()
    }   
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多