简体   繁体   中英

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?
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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