我在OSX 10.12.3上的MacOS / OSX应用程序中使用RealmSwift,当我尝试从数据库中获取对象时,Realm会因未捕获的异常而崩溃。
这是在get object func上崩溃的代码片段:
private var database: Realm!
init(some_var: String) {
var configuration = Realm.Configuration()
configuration.fileURL = configuration.fileURL!.deletingLastPathComponent().appendingPathComponent("\(some_var).realm")
do {
debugPrint("Inside init: Current thread \(Thread.current)")
self.database = try Realm(configuration: configuration)
} catch {
debugPrint("realmInit: Can't create realm database.")
}
}
func getObject<T: Object, K>(with primaryKey: K) -> T? {
debugPrint("Inside getObject: Current thread \(Thread.current)")
return self.database.object(ofType: T.self, forPrimaryKey: primaryKey) // THIS LINE THROWS EXCEPTION
}
我因未捕获的异常而崩溃:
"Inside init: Current thread <NSThread: 0x600000075700>{number = 5, name = (null)}"
"Inside getObject: Current thread <NSThread: 0x600000075700>{number = 5, name = (null)}"
libc++abi.dylib: terminating with uncaught exception of type NSException
起初我认为这是一个线程问题,但你可以看到我在同一个线程上启动了Realm和getObject。
请问任何帮助吗?
答案 0 :(得分:0)
原来问题是返回类型为 可选通用 。
在与github上的Realm库的一个贡献者进行对话后,听起来它可能是一个RealmSwift错误。
此处已提出问题https://github.com/realm/realm-cocoa/issues/4951
解决方法是实现一个函数,如果对象存在,则返回Bool
,然后返回非可选泛型,如果不存在则创建新对象。