Search code examples
swiftcore-datarealm

How to save dinamically array in core data or realm in iOS And how to compare this array


I have an array

var names:[String]=["kate","son","viktor"]

I want to save this array in core data or Realm. This array dynamically changed

var names:[String]=["kate","son","viktor","sam"]

How to compare this arrays and print changes. For example: changes for names "Sam". Thanks for any help(idea) or links.


Solution

  • In Realm, you could simply serialize/deserialize the array to Data (or String), like this:

    class SomeModel: Object {
        dynamic var _names: Data!
    
        var names: [String] {
            set(value) {
                try! realm.write {
                    _properties = try! JSONSerialization.data(withJSONObject: value, options: [])
                }
            }
            get {
                guard _names != nil else { return [] }
                return try! JSONSerialization.jsonObject(with: _names, options: []) as? [String] ?? []
            }
        }
    }
    

    This will store your array in Realm, but will not allow you to sort or query using the names in the array, obviously.

    You probably better store each name in a proper model object and create a one-to-many property in the base object (using Realm's List)