我有一个带有 today 扩展的应用程序。在 MainApp 的 AppDelegate.swift
中:
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 中工作,当我想在今天的扩展中使用它时,我在通知中心得到 Unable to load
。
问题是 Realm,因为当我从代码中删除 let realmContext = ...
时,今天的扩展没有问题。
怎么了?
最佳答案
这可能是由于内存不足。 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)
...
关于ios - 在 iOS Today 扩展中使用 Realm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41815427/