Search code examples
iosswiftrealmrealm-mobile-platform

why I need required initializer when creating Realm Data Model?


I am new in iOS development, and I just follow along a tutorial on the internet

my data model before implementing realm is like this

import Foundation
import FirebaseFirestore

class CityKM {
    var name : String
    var coordinate : GeoPoint

    init (name: String , coordinate: GeoPoint ) {
        self.name = name
        self.coordinate = coordinate
    }

    init (dictionary: [String:Any]) {
        // this init will be used if we get data from firebase  to construct a city object

        name = dictionary["name"] as! String
        coordinate = dictionary["coordinate"] as! GeoPoint
    }


   }

and after implementing Import RealmSwift, my class should be like this by subclassing Object from realm

import Foundation
import FirebaseFirestore
import RealmSwift


class CityKM : Object {
    @objc dynamic var name : String = ""
    @objc dynamic var var coordinate : GeoPoint = Geopoint(latitude: 6.01212, Longitude: -101.212)

    init (name: String , coordinate: GeoPoint ) {
        self.name = name
        self.coordinate = coordinate
    }

    init (dictionary: [String:Any]) {
        // this init will be used if we get data from firebase  to construct a city object

        name = dictionary["name"] as! String
        coordinate = dictionary["coordinate"] as! GeoPoint
    }


   }

but I don't why it always give an error that said my CityKM class should have required initializer

required' initializer 'init()' must be provided by subclass of 'Object'

if I fix the error and follow the fix instruction from xcode, the error will still there and I don't know how to fix this like the picture below

enter image description here

what went wrong and what should I do ?


Solution

  • Try to declare your CityKM class like this

    Here you will find an explanation of why it was used convenience Initialization Apple

      class CityKM : Object {
        @objc dynamic var name : String = ""
        @objc dynamic var let coordinate : GeoPoint = Geopoint(latitude: 6.01212, Longitude: -101.212)
    
        convenience init (name: String , coordinate: GeoPoint ) {
            self.init()
            self.name = name
            self.coordinate = coordinate
        }
    
       convenience init (dictionary: [String:Any]) {
         self.init()
            // this init will be used if we get data from firebase  to construct a city object
    
            name = dictionary["name"] as! String
            coordinate = dictionary["coordinate"] as! GeoPoint
        }
    
    
    }