使用主键检索单个Realm对象-错误:无效对象ID字符串必须是24个十六进制数字



我正在尝试使用主键获得单个对象,但它从来没有工作,无法找出我错过了什么

我的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()通过chapterID作为主键检索对象时。object(ofType:forPrimaryKey:)或Realm的实例。我得到了以下错误。例如:for id 2

无效对象ID字符串'2':必须是24位十六进制数字

谢谢你的建议

chapterIDInt,所以当你试图获取Chapter时,你不应该传递String。只需传递一个整数值。

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

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

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