Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - Object type 'RealmSwiftObject' is not managed by the Realm exception

Tags:

ios

swift

realm

I am using Realm with Swift 3 in my iOS app. I have the following code

//Find all records for the day
func findForToday<T: Object>() -> [T] {
    let predicate = NSPredicate(format: "date >= %@ and date <= %@", DateUtil.dayStart(), DateUtil.dayEnd())
    return getRealm().objects(T.self).filter(predicate).map { $0 }
}

where T in this context is my realm model class which look like

class MyModel : Object {

    dynamic var id = 0
    dynamic var date = NSDate()

    override class func primaryKey() -> String? {
        return "id"
    }

}

I am getting an exception at run time saying

Terminating app due to uncaught exception 'RLMException', reason: 
'Object type 'RealmSwiftObject' is not managed by the Realm. If using a custom 
`objectClasses` / `objectTypes` array in your configuration, add `RealmSwiftObject`
to the list of `objectClasses` / `objectTypes`.'
like image 675
Jaseem Abbas Avatar asked Oct 10 '16 14:10

Jaseem Abbas


2 Answers

The error message is indicating that T has been inferred as Object rather than MyModel, so you will need to adjust the call site to ensure Swift picks the correct type.

like image 145
Thomas Goyne Avatar answered Nov 05 '22 05:11

Thomas Goyne


The question is pretty old but it looks like you did not add your object to the Realm configuration:

var realmOnDisc: Realm? {
        let url = ...URL to your file
        let objectTypes = [MyModel.self, SomeOtherModel.self] 
        let config = Realm.Configuration(fileURL: url, 
                                         deleteRealmIfMigrationNeeded:true, 
                                         objectTypes: objectTypes)

        do {
            let realm = try Realm(configuration: config)
            return realm 
        } catch let error {
            log.error("\(error)")
            return nil
        }
    }
like image 3
Yurii Koval Avatar answered Nov 05 '22 07:11

Yurii Koval