swift-sdk
swift-sdk copied to clipboard
Stopping Core Data Crashes When Disk is Full
Description
This PR prevents a crash which occurs when Core Data's persistent store fails to load. Loading the persistent store can fail for several reasons: the database could be corrupted, the disk might be full, or from a bad migration. This also might occur when the app wakes up in the background and the persistent store didn't load in time.
When using NSPersistentContainer it's important to handle any errors from loadPersistentStores(_:) since they're recoverable. If you ignore this error, then Core Data throws an Objective-C exception which cannot be handled in Swift when you try to save.
Previous PR #816
Crash
The crash originates from IterableTaskScheduler.deleteAllTasks() which calls try persistenceContext.save() and throws:
NSInternalInconsistencyException - This NSPersistentStoreCoordinator has no persistent stores (disk full). It cannot perform a save operation.
Fatal Exception: NSInternalInconsistencyException
0 CoreFoundation 0x9cb4 __exceptionPreprocess
1 libobjc.A.dylib 0x183d0 objc_exception_throw
2 CoreData 0x192388 -[NSPersistentStoreCoordinator _introspectLastErrorAndThrow]
3 CoreData 0x19288c __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke.551
4 CoreData 0x5f678 -[NSPersistentStoreCoordinator _routeHeavyweightBlock:]
5 CoreData 0x256d8 -[NSPersistentStoreCoordinator executeRequest:withContext:error:]
6 CoreData 0x256fc -[NSPersistentStoreCoordinator executeRequest:withContext:error:]
7 CoreData 0x88220 -[NSManagedObjectContext save:]
8 Fetch Rewards 0x1876084 closure #1 in IterableTaskScheduler.deleteAllTasks() + 177 (IterableCoreDataPersistence.swift:177)
9 Fetch Rewards 0x18c3dcc thunk for @escaping @callee_guaranteed () -> () (<compiler-generated>)
10 CoreData 0x80b6c developerSubmittedBlockToNSManagedObjectContextPerform
11 libdispatch.dylib 0x3eac _dispatch_client_callout
12 libdispatch.dylib 0xb534 _dispatch_lane_serial_drain
13 libdispatch.dylib 0xc0a4 _dispatch_lane_invoke
14 libdispatch.dylib 0x16cdc _dispatch_workloop_worker_thread
15 libsystem_pthread.dylib 0xddc _pthread_wqthread
16 libsystem_pthread.dylib 0xb7c start_wqthread