簡體   English   中英

如何從用戶默認值swift3的字典數組中刪除特定鍵值

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

我有一個保存在“用戶默認值”中的字典數組。 我在UITableview中顯示這些值。 當用戶右鍵滑動表格單元格並將其刪除時,該單元格已成功刪除,但實際上並未從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
    }

這對我有用。 謝謝@ 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