首页 > 解决方案 > Save selected items in array of objects to UserDefaults in swift 4

问题描述

I have decoded my Json to structure and now I have array of objects that each objects has some values so I want when user select item in collection View the selected object in array append to the array of objects in UserDefaults I read similar questions so I used this Function Below But it won't work

@objc func likeOrDislike (_ sender : UIButton!) {
    let arrays = UserDefaults.standard.value(forKey: "Liked") as? [ListsModel.ResultValue]
    print(arrays as Any)
    var items = arrays
    let item = self.adv.resultValue[sender.tag]
    if arrays != nil {
        if items!.contains(where: {($0.id == item.id)}) {
            items!.filter({($0.id == item.id)})
        } else {
            items!.append(item)
        }
    } else {
       items = [item]
    }
    UserDefaults.standard.setValue(items, forKey: "Liked")
    UserDefaults.standard.synchronize()
}

and here is the model that I use for decode

public class ListsModel {
  struct Response : Decodable {
    var resultValue : [ResultValue]
  }

  struct ResultValue : Decodable {
    let id : String?
    let title : String?
    let user_id : String?
    let username : String?
    let user_image : String?
    let release_date : String?
    let start_date : String?
    let salary : String?
    let salary_id : String?
    let work_field_id : String?
    let adv_type_id : String?
    let work_field : String?
    let description : String?
    let adv_base_id : String?
    let is_spec : String?
    let status : String?
    let p_expire_date : String?
  }
}

标签: iosswiftnsuserdefaultsarrayobject

解决方案


通过 stringify 将所有模型对象转换为字符串,然后存储到用户默认值并在您想要使用的地方使用。


推荐阅读