【问题标题】:NSInternalInconsistencyException causing crash even though it's wrapped in do-try-catchNSInternalInconsistencyException 导致崩溃,即使它被包裹在 do-try-catch 中
【发布时间】:2021-07-22 20:29:45
【问题描述】:
// context is an instance of NSManagedObjectContext
context.performAndWait {
    do {
        guard context.hasChanges else {
            return
        }
        try context.save()
    } catch {
        print("Error...")
    }
}

有谁明白为什么包含try context.save() 的行似乎会导致以下崩溃?

致命异常:NSInternalInconsistencyException 这 NSPersistentStoreCoordinator 没有持久存储(磁盘已满)。它 无法执行保存操作

这是堆栈跟踪的一部分:

Fatal Exception: NSInternalInconsistencyException
0  CoreFoundation                 0x19d4c99d8 __exceptionPreprocess
1  libobjc.A.dylib                0x1b184fb54 objc_exception_throw
2  CoreData                       0x1a33b42d8 -[NSPersistentStoreCoordinator _coordinator_you_never_successfully_opened_the_database_io_error:]
3  CoreData                       0x1a33b4370 -[NSPersistentStoreCoordinator _introspectLastErrorAndThrow]
4  CoreData                       0x1a33b49c8 __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke.797
5  CoreData                       0x1a324b408 -[NSPersistentStoreCoordinator _routeHeavyweightBlock:]
6  CoreData                       0x1a324c2d0 -[NSPersistentStoreCoordinator executeRequest:withContext:error:]
7  CoreData                       0x1a324c2fc -[NSPersistentStoreCoordinator executeRequest:withContext:error:]
8  CoreData                       0x1a324d270 -[NSManagedObjectContext save:]

throwing 方法被包装在一个 do-try-catch 中,这应该可以防止应用程序崩溃,但 Firebase (Crashlytics) 将其报告为崩溃。

【问题讨论】:

  • 因为不是(NS)Error,而是NSInternalInconsistencyExceptionNSException。你抓不到他们。使用您的do/try/catch,您将捕捉到(NS)Error 此处save 的尝试方法抛出的内容。但这就是崩溃,而不是抛出错误。这就是快速解释。
  • 现在您看到了差异:stackoverflow.com/questions/32758811/… 等。对于您的问题,这意味着您可能需要解决比简单的 try/catch 更大的问题。
  • 您最终是否在 Crashlytics 中看到了更多此类崩溃,或者这是自发的异常值?我刚刚收到此崩溃报告 1 次,并注意到用户设备剩余的磁盘空间非常少 - 想知道它是否相关
  • 此崩溃有多个实例。我认为与磁盘空间不足有关,因为异常提到磁盘已满。

标签: ios swift core-data crash


【解决方案1】:

NSExceptions 不被do/catch 子句处理; Errors 是。

不过,您可以使用 Objective-C 子句捕获 NSExceptions,但通常它们对于从实际的潜在问题中恢复是无用的;相反,他们只是压制它。

如果您有这样的异常,那么您在代码的其他地方出错了。要真正阻止异常的发生,您需要修复该错误。在您的情况下,可以在堆栈跟踪中观察到有问题的问题:

_coordinator_you_never_successfully_opened_the_database_io_error

这暗示您的应用可能没有正确设置您的持久存储。可能是在应用初始加载期间,您的NSPersistentStoreCoordinatoraddPersistentStore 方法发生了I/O 错误,而您没有处理?

【讨论】:

    猜你喜欢
    • 2016-03-19
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多