【问题标题】:Realm Swift crashing with uncaught exception when trying to get object尝试获取对象时,Realm Swift 因未捕获的异常而崩溃
【发布时间】:2017-05-12 04:03:25
【问题描述】:

我在 OSX 10.12.3 上的 MacOS/OSX 应用程序中使用 RealmSwift,当我尝试从数据库中获取对象时,Realm 崩溃并出现未捕获的异常。

这是在获取对象函数上崩溃的代码 sn-p:

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。

任何帮助将不胜感激?

【问题讨论】:

  • 很可能是 configuration.fileURL == nil,为什么你使用奇怪的强制展开?
  • 有趣,我会尝试看看是否是问题所在,然后回复我的发现。不太清楚为什么我要强行打开那个 tbh,我想我一定是从某个地方的样品上拿下来的。
  • 这并不是问题所在,请参阅下面的答案。

标签: swift macos realm


【解决方案1】:

原来问题在于返回类型是可选的泛型

在与 github 上 Realm 库的一位贡献者交谈后,听起来这可能是一个 RealmSwift 错误。

问题已经在这里提出https://github.com/realm/realm-cocoa/issues/4951

解决方法是实现一个函数,如果对象存在则返回一个Bool,然后在它存在时返回一个非可选的泛型,如果它不存在则创建一个新对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多