iOS Swift将Realm对象存储到UserDefaults.standard

时间:2017-04-07 08:51:16

标签: ios swift3 realm nsuserdefaults

这是我的Realm对象:

PracticeAreaEntity {
    id = 0;
    c_id = 21871;
    c_number = C.C/1/2016;
    c_title = Title Here;
    date = 2017-04-07T00:00:00.000Z;
    description2 = ;
    object = {"id":205039,"c_id":21871,"name":"07-04-2017","s_time":"2017-04-07T00:00:00.000Z","e_time":"2017-04-08T00:00:00.000Z","creator":"system","created_by_id":null,"description":null,"c_at":"2017-03-26T00:11:52.134Z","u_at":"2017-04-07T01:00:27.396Z","judge":null,"phearing":null,"google_event_id":null,"is_completed":false,"business":null,"last_notified":"2017-04-07T01:00:27.382Z","ng_date":null,"b_date":null,"b_d_available":false};
    p_id = 205039;
    subject = 07-04-2017;
    type = Event;
}

我需要将此域对象存储到UserDefault.standard并在另一个页面中获取值。这是我的UserDefults代码:

let userDefaults = UserDefaults.standard
userDefaults.set(filteredtotalContactArray[indexPath.row], forKey: "SelectedPractice")
userDefaults.synchronize()

filteredtotalContactArray [indexPath.row]等于我之前指定为Realm Object的值。但是我收到了错误

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object 

1 个答案:

答案 0 :(得分:1)

您需要为您的Realm模型提供NSCoding的一致性方法,以便能够将它们保存到UserDefaults

但是,我鼓励您使用Realm来保留Realm模型,因为您已经在应用中使用了Realm。