我在 OSX 10.12.3 上的 MacOS/OSX 应用程序中使用 RealmSwift,当我尝试从数据库获取对象时,Realm 崩溃并出现未捕获的异常。
这是在获取对象函数上崩溃的代码片段:
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。
如有任何帮助,我们将不胜感激?
最佳答案
事实证明,问题在于返回类型是可选泛型。
与 github 上 Realm 库的一位贡献者交谈后,听起来这可能是一个 RealmSwift 错误。
问题已在此处提出 https://github.com/realm/realm-cocoa/issues/4951
解决方法是实现一个函数,如果对象存在,则返回一个 Bool
,然后在存在时返回一个非可选泛型,如果不存在则创建一个新对象。
关于swift - Realm Swift 在尝试获取对象时因未捕获的异常而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43929091/