iOS开发:Realm数据模型为何需required初始化器及解决办法
Hey there! I see you're running into an issue converting your Firebase model to a Realm Object subclass—let's break down what's going on and fix it step by step.
Why the Error Occurs
Realm's Object class enforces that all subclasses provide a no-argument init() initializer because Realm relies on this internally to create instances when loading data from the database. When you define custom designated initializers (like your init(name:coordinate:) and init(dictionary:)), Swift automatically removes the default no-argument initializer inherited from Object. Even if you used Xcode's auto-fix, you might have missed a critical detail: the initializer needs to be marked required and must call super.init() to properly initialize the parent Object class.
I also spotted two typos in your code that would cause extra errors:
Geopointshould beGeoPoint(capital 'P'—Firebase's location type is spelledGeoPoint)Longitudein your default coordinate should belongitude(lowercase 'l'—the parameter name is case-sensitive)
Fixed Code Implementation
Here's the corrected version of your CityKM class that resolves all issues:
import Foundation import FirebaseFirestore import RealmSwift class CityKM: Object { @objc dynamic var name: String = "" @objc dynamic var coordinate: GeoPoint = GeoPoint(latitude: 6.01212, longitude: -101.212) // Required no-argument initializer for Realm required init() { super.init() } init(name: String, coordinate: GeoPoint) { super.init() self.name = name self.coordinate = coordinate } init(dictionary: [String: Any]) { super.init() // Use optional binding instead of force-unwrapping to avoid crashes if let nameValue = dictionary["name"] as? String { self.name = nameValue } if let coordinateValue = dictionary["coordinate"] as? GeoPoint { self.coordinate = coordinateValue } } // Optional: Define a primary key if you want Realm to uniquely identify objects override class func primaryKey() -> String? { return "name" } }
Key Changes Explained
- Added
required init(): This satisfies Realm's mandatory requirement for a no-argument initializer. Callingsuper.init()ensures the parentObjectclass is properly initialized. - Corrected typos: Fixed the case issues with
GeoPointandlongitudeto match Firebase's API specifications. - Safer dictionary initialization: Replaced risky force-unwraps (
as!) with optional binding (as?) to prevent crashes if Firebase returns missing or incorrectly formatted data. - Optional primary key: Added an override for
primaryKey()(optional but useful) to help Realm track unique objects, which simplifies updates and avoids duplicates.
Why Xcode's Auto-Fix Might Have Failed
If you used Xcode's "Fix" suggestion, it likely added a required init() without including super.init(). This is invalid because Object's initializer must be invoked to set up the Realm object properly—our fixed version includes this critical call.
内容的提问来源于stack exchange,提问作者Agung

