如何从用户默认值swift3中删除字典数组中的特定键值

时间:2018-02-04 06:42:35

标签: ios swift uitableview nsdictionary nsuserdefaults

我在“用户默认值”中保存了一个字典数组。我在UITableview中展示了这些价值。当用户右键滑动表格单元格并将其删除时,该单元格已成功删除,但实际上并未从“用户默认值”中删除。这是我尝试的内容:

   var notificationArray: [[String: AnyObject]] = []
   var title = [String]()
   var detail = [String]()

   override func viewDidLoad() {
     super.viewDidLoad()
      if let tempArray = UserDefaults().array(forKey: "notificationArray") as? [[String: AnyObject]] {

        notificationArray = tempArray

         self.title = tempArray.flatMap { $0["title"] as? String }
         self.detail = tempArray.flatMap { $0["detail"] as? String }
    }
  }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")

        self.title.remove(at: indexPath.row)
        self.detail.remove(at: indexPath.row)
        self.tableView.deleteRows(at: [indexPath], with: .automatic)

       notificationArray.append(["title": title as AnyObject, "detail": detail as AnyObject]) 
       UserDefaults.standard.set(notificationArray, forKey: "notificationArray")       
          print("title, detail", title, detail)       
    }
}

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return title.count
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
       return 80
     }

    override func numberOfSections(in tableView: UITableView) -> Int {
       return 1
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

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


        cell.notificationTittleLabel.text = title[indexPath.row]
        cell.notificationDetailLabel.text = detail[indexPath.row]

        cell.backgroundColor = UIColor.clear

        return cell
    }

1 个答案:

答案 0 :(得分:0)

这对我有用。谢谢,@ Paulw11:)

  var myNotificationArray = UserDefaults.standard.object(forKey: "notificationArray") as? [AnyHashable]
  myNotificationArray?.remove(at: indexPath.row) 
  UserDefaults.standard.set(myNotificationArray, forKey: "notificationArray") 
  UserDefaults.standard.synchronize()