【问题标题】:Realm must not be nil领域不能为零
【发布时间】:2016-10-26 09:24:14
【问题描述】:

我从 Realm 0.9x но 2.0.x 更新了我的应用程序 现在我在 Crashlytics 上收到了大量来自 8、9 和 10 台 iOS 设备的关于致命异常的错误报告:

Fatal Exception: RLMException
Realm must not be nil

堆栈跟踪如下所示:

RLMObjectStore.mm 第 81 行 RLMGetObjects

RLMObject.mm 第 154 行 +[RLMObject objectsInRealm:withPredicate:]

RLMObject.mm 第 146 行 +[RLMObject objectsInRealm:where:args:]

RLMObject.mm 第 140 行 +[RLMObject objectsInRealm:where:]

Sessions.m 第 88 行 +[会话结果WithSessionsWhere:]

Sessions.m 第 128 行 +[会话活动会话]

Sessions.m 第 102 行 +[会话应用启动]

AppDelegate.m 第 60 行 -[AppDelegate 应用程序:didFinishLaunchingWithOptions:]

我无法在调试环境中重现错误。它触及了大约 30-40% 的用户(根本没有),而且我似乎只触及了老用户。

此方法中没有领域对象:

/**
 *  Create and returns Realm configuration for sessions database
 */
+(nonnull RLMRealmConfiguration*)realmConfigurationForSessions
{
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    // Use the default directory, but replace the filename with the 'sessions.realm'
    config.fileURL = [NSURL
                  URLWithString:[[[config.fileURL.absoluteString stringByDeletingLastPathComponent]
                                      stringByAppendingPathComponent:@"sessions"]
                                     stringByAppendingPathExtension:@"realm"]];
    return config;
}

+(nullable RLMRealm*)realmForConfiguration:(nullable RLMRealmConfiguration*)config
{
    if (!config) {
        return nil;
    }
    NSError *error;
    // Open the Realm with the configuration
    RLMRealm *realm = [RLMRealm realmWithConfiguration:config
                                                 error:&error];
    if (error) {
        DLog(@"error: %@", error.localizedDescription);
    }
    return realm;
}

问题:1)这个奇怪问题的原因是什么? 2) 在这种情况下如何正确处理错误和 nil 领域值?

【问题讨论】:

    标签: ios objective-c realm


    【解决方案1】:

    那个例外occurs in a pretty straightforward case。发生错误,导致 RLMRealm 实例未在本应创建的情况下创建。

    根据您提供的信息,您构建 fileURL 属性的方式可能不会在所有情况下都成功。

    我的建议:

    • 使用[NSURL fileURLWithPath:] 而不是[NSURL URLWithString:]。与 Web URL 相比,该文件路径更适合文件路径。
    • 使用config.fileURL.path 而不是config.fileURL.absoluteString。欲知详情,请check this SO answer
    • 为保持一致性,请使用 [NSURL URLByAppendingPathComponent:] 而不是 [NSString stringByAppendingPathComponent:]

    希望对您有所帮助!如果您需要进一步说明,请告诉我!

    【讨论】:

    • 好的,很好。但是错误处理呢?如果出现错误,如何获得稳定运行的应用程序?
    • [RLMRealm realmWithConfiguration: error:] 如果发生错误将返回nil,因此很容易检测是否发生了阻止生成领域的错误,因此您可以缓解它。在这种情况下,(除非其他地方出现其他问题)它只会在fileURL 未正确格式化并指向磁盘上的有效位置时才会发生。因此,在这种情况下,在将 NSURL 值传递给 Realm 之前验证它可能会有所帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多