0

Here is my Realm Object:

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

I need to store this realm object to UserDefault.standard and get values back in another page. And here is my UserDefults code:

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

filteredtotalContactArray[indexPath.row] equals to values that I have specified before as Realm Object. But I am getting error as

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object 
Kavin Kumar Arumugam
  • 1,792
  • 3
  • 28
  • 47
  • 1
    Why are u try to store the object in `UserDefault ` while using `Realm`? Thats a bad practice, also, store custom object in `UserDefault` require confront to `NSCoding` protocol, which will convert your object into Data – Tj3n Apr 07 '17 at 09:17
  • In tableview I'm displaying list of object in my realm. I need to store selected index path.row value into UserDefaults.standard – Kavin Kumar Arumugam Apr 07 '17 at 09:29
  • we can't store custom object directly, you need to go for Keyarchiver concept – Anbu.Karthik Apr 07 '17 at 09:45
  • 1
    see this http://stackoverflow.com/questions/37980432/swift-3-saving-and-retrieving-custom-object-from-userdefaults – Anbu.Karthik Apr 07 '17 at 09:48
  • I have try that too. Here is the code to store values: `let userDefaults = UserDefaults.standard let encodedData = NSKeyedArchiver.archivedData(withRootObject: (filteredtotalContactArray[indexPath.row] as AnyObject)) userDefaults.set(encodedData, forKey: "SelectedPractice") userDefaults.synchronize()` But it won't works – Kavin Kumar Arumugam Apr 07 '17 at 09:50

1 Answers1

1

You'll need to supply conformance methods to NSCoding for your Realm models in order to be able to persist them to UserDefaults.

However, I'd encourage you to use Realm to persist Realm models given that you're already using Realm in your app.

jpsim
  • 14,329
  • 6
  • 51
  • 68