ios - 在 iOS Today 扩展中使用 Realm

标签 ios swift realm

我有一个带有 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/

相关文章:

ios - 点击时从 UITableViewCell 内的 UICollectionView 推送到新的 UIViewController

ios - getter setter 模型类 Oop

swift - 如何在 swift 中进行 CNAME 记录查找

Realm 的 kotlin 中的 Android 测试

ios - 如何在一定时间后在后台杀死/停止应用程序

ios - 第一次应用程序更新,用户数据丢失(存储在 Documents 目录中)

arrays - swift 平面 map : How to remove only tuples from an array where specific element in the tuple is nil?

ios - 如何使用 Core Data 中的数据填充 TextField 并更新更改?

ios - 从 Realm 中删除模型,但让对象保持事件状态

ios - 将所有对象从一个 Realm 复制到另一个 Realm