NSInternalInconsistencyException 导致崩溃,即使它被包裹在 do-try-catch 中

NSInternalInconsistencyException causing crash even though it's wrapped in do-try-catch

// context is an instance of NSManagedObjectContext
context.performAndWait {
    do {
        guard context.hasChanges else {
            return
        }
        try context.save()
    } catch {
        print("Error...")
    }
}

有谁知道为什么包含 try context.save() 的行会导致以下崩溃?

Fatal Exception: NSInternalInconsistencyException This NSPersistentStoreCoordinator has no persistent stores (disk full). It cannot perform a save operation

这是堆栈跟踪的一部分:

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) 将其报告为崩溃。

NSException 不由 do/catch 子句处理; Error是。

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

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

_coordinator_you_never_successfully_opened_the_database_io_error

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