Home > Software design >  Retrieve a single Realm object using Primary key - Error : Invalid Object ID string must be 24 hex d
Retrieve a single Realm object using Primary key - Error : Invalid Object ID string must be 24 hex d

Time:10-13

I am trying to get a single object using primary key but it never works and cannot figure out what I missed

My Realm data model is as follows

class Chapter : Object {
    @objc dynamic var title = ""
    @objc dynamic var chapterID = 0
    @objc dynamic var bookmark =  0.0
    @objc dynamic var marked = false
    
    
    let notes = List<Notes>()
    
    
    override class func primaryKey() -> String? {
        return "chapterID"
    }
} 


 func addNote(note: Note, chapterID: Int ) {
        
    objectWillChange.send()
 
    do {
  
      
let chapter = try Realm().object(ofType: Chapter.self, forPrimaryKey: "\(chapterID)")
//  code to append note 

}
catch let error {
      // Handle error
      print("Error in retrieving chapter no. \(chapterID)")
      print(error.localizedDescription)
    }

When I try to retrieve object by chapterID as primary key using Realm().object(ofType: forPrimaryKey:) or instance of Realm realm.object(ofType:forPrimaryKey: I got the following error. e.g. for id 2

Invalid Object ID string '2': must be 24 hex digits

Thanks for any tips

CodePudding user response:

chapterID is an Int so you shouldn't be passing a String when you try to fetch the Chapter. Just pass in an integer value.

let chapter = try Realm().object(ofType: Chapter.self, forPrimaryKey: chapterID)

Depending on which Realm you are using, I would recommend the newer syntax:

class Chapter: Object {
    @Persisted var title = ""
    @Persisted(primaryKey: true) var chapterID = 0
    @Persisted var bookmark =  0.0
    @Persisted var marked = false
}
  • Related