Jaseem Abbas
Jaseem Abbas

Reputation: 5230

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

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`.'

Upvotes: 6

Views: 5457

Answers (3)

Yurii Koval
Yurii Koval

Reputation: 429

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

Upvotes: 4

Pavel Kandziuba
Pavel Kandziuba

Reputation: 141

Hi just resolved such issue. In my case if I call your func "findForToday" like

let myArray = MyModel().findForToday() and i got same error

but after i specified value type error lost.

let myArray : AnyRealmCollection < MyModel> = MyModel().findForToday()

Upvotes: 0

Thomas Goyne
Thomas Goyne

Reputation: 8138

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.

Upvotes: 5

Related Questions