Retrieve a single Realm object using Primary key - Error : Invalid Object ID string must be 24 hex digits

Retrieve a single Realm object using Primary key - Error : Invalid Object ID string must be 24 hex digits

我正在尝试使用主键获取单个对象,但它永远不起作用,无法弄清楚我错过了什么

我的Realm数据模型如下

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

当我尝试使用 Realm().object(ofType: forPrimaryKey:) 或 Realm realm.object(ofType:forPrimaryKey: 我收到以下错误。例如对于 id 2

无效的对象 ID 字符串“2”:必须是 24 个十六进制数字

感谢任何提示

chapterID 是一个 Int,因此当您尝试获取 Chapter 时不应传递 String。只需传入一个整数值即可。

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

根据您使用的领域,我建议使用较新的语法:

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