2017-05-12 34 views
0

我在OSX 10.12.3的MacOS/OSX應用程序中使用RealmSwift,當嘗試從數據庫獲取對象時,Realm與未捕獲的異常崩潰。Realm Swift在嘗試獲取對象時遇到未捕獲的異常

下面的代碼片段,在獲取對象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。

任何幫助,將不勝感激請嗎?

+1

最有可能的配置.fileURL ==零,爲什麼你使用奇怪的強制解包? – user3441734

+0

有趣的,我會嘗試,看看是否是這個問題,並回復我找到的東西。我不知道爲什麼我強迫打開那個tbh,我想我只是在某個地方抓住了它。 – Gix

+0

這並不是問題所在,請參閱下面的答案。 – Gix

回答

0

原來的問題是返回類型是可選的通用

在與github上的Realm庫的貢獻者交談之後,聽起來它可能是RealmSwift的bug。

問題已經在這裏提出https://github.com/realm/realm-cocoa/issues/4951

解決方法是實施如果對象存在,它返回一個Bool一個函數,然後返回一個非可選通用當它,而創建新的對象,如果它不」不存在。