2017-01-23 57 views
1

我有一個今日擴展的應用程序。在MainApp的AppDelegate.swift在iOS今日擴展中使用領域

let realmContext = try! Realm(fileURL: NSFileManager 
     .defaultManager() 
     .containerURLForSecurityApplicationGroupIdentifier("group.this.is.test")! 
     .URLByAppendingPathComponent("db.realm")) 

在我todayExtension的viewDidLoad:

let realmContext = try! Realm(fileURL: NSFileManager 
     .defaultManager() 
     .containerURLForSecurityApplicationGroupIdentifier("group.this.is.test")! 
     .URLByAppendingPathComponent("db.realm")) 

那些完全相同。但是,它在MainApp中起作用,並且當我想在今天的擴展中使用它時,我在Notification Center中獲得Unable to load。 問題是領域,因爲當我從代碼中刪除let realmContext = ...,今天擴展沒有問題。 有什麼不對?

+0

確保App Group在您今天的擴展中正確配置。你還可以提供你在Xcode控制檯中看到的任何錯誤消息嗎? – Dmitry

回答

1

這可能是由於內存耗盡。 Realm(fileURL:)在內部調用objc_copyClassList(),它需要大量的內存。它偶爾會在應用程序擴展上失敗,因爲內存在應用程序擴展上受到嚴格限制(非常少)。

爲了避免這種情況,您可以使用Realm.Configuration中的objectTypes設置明確指定模式。在明確給出模式時,Realm不會調用objc_copyClassList(),因爲不需要枚舉所有類。

let config = Realm.Configuration(
    fileURL: NSFileManager 
     .defaultManager() 
     .containerURLForSecurityApplicationGroupIdentifier("group.this.is.test")! 
     .URLByAppendingPathComponent("db.realm"), 
    objectTypes: [SomeClass.self, AnotherClass.self]) 
let realm = try Realm(configuration: config) 
...