简体   繁体   English

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

[英]How to remove specific key value from array of dictionary from User Defaults swift3

I have an array of dictionary saved in User Defaults. 我有一个保存在“用户默认值”中的字典数组。 I am showing these value in UITableview. 我在UITableview中显示这些值。 When the user right swipes the table cell and remove it, the cell is successfully deleted, but it is not actually deleted from User Defaults.Here what I tried : 当用户右键滑动表格单元格并将其删除时,该单元格已成功删除,但实际上并未从User Defaults中删除。

   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
    }

This is worked for me. 这对我有用。 Thanks, @Paulw11 :) 谢谢@ Paulw11 :)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM