Exception Type: EXC_BAD_ACCESS
Exception Subtype: KERN_INVALID_ADDRESS 0x00000003d74249bd
Release Type: User
Realm framework version: 10.5.1
Xcode version: 12.3
iOS/OSX version: 14.3
-->
Crash on transaction
Crashed: com.apple.root.background-qos
0 Realm 0x1058abfb8 realm::Allocator::translate_less_critical(realm::Allocator::RefTranslation*, unsigned long) const + 68
1 Realm 0x1057fce30 realm::Array::init_from_ref(unsigned long) + 192
2 Realm 0x105ca356c realm::_impl::GroupFriend::get_history_ref(realm::Allocator&, unsigned long) + 68
3 Realm 0x105c3ba60 bool realm::Transaction::internal_advance_read<(anonymous namespace)::TransactLogValidator>((anonymous namespace)::TransactLogValidator*, realm::VersionID, realm::_impl::History&, bool) + 176
4 Realm 0x105c36400 realm::_impl::transaction::begin(std::__1::shared_ptrrealm::Transaction const&, realm::BindingContext*, realm::_impl::NotifierPackage&) + 416
5 Realm 0x105c2b77c realm::_impl::RealmCoordinator::promote_to_write(realm::Realm&) + 268
6 Realm 0x105ca1570 realm::Realm::begin_transaction() + 404
7 Realm 0x10588ee24 -[RLMRealm beginWriteTransactionWithError:] + 24
8 Inventa 0x10510b0a0 $s7Inventa15RealmDataHelperC33saveDataAA0I0CG_tFyycfU_Tf2i_n + 52
9 Inventa 0x1050c2c98 $sIeg_IeyB_TR + 20
10 libdispatch.dylib 0x19941c24c _dispatch_call_block_and_release + 32
11 libdispatch.dylib 0x19941ddb0 _dispatch_client_callout + 20
12 libdispatch.dylib 0x19942ea68 _dispatch_root_queue_drain + 656
13 libdispatch.dylib 0x19942f120 _dispatch_worker_thread2 + 116
14 libsystem_pthread.dylib 0x1e52d97d8 _pthread_wqthread + 216
15 libsystem_pthread.dylib 0x1e52e076c start_wqthread + 8
func Inventa15RealmDataHelperC33saveData(notifications: [Notifications]) {
Inventa23.shared56.realmHelper.removeStaleDistinctNotifications654(notificationsofZone: "ezone")
var filtered:[Notifications] = []
for notif in notifications {
for stId in notif.st_ids {
notif.stId = stId
notif.notif_key = "\(notif.ntId)-\(notif.stId))"
filtered.append(notif)
}
}
let backgroundQueue = DispatchQueue.global(qos: .background)
backgroundQueue.async(execute: {
do{
let realm = try Realm()
realm.beginWrite()
realm.add(filtered, update: .all)
try realm.commitWrite()
}
catch{
print(error)
}
})
}
internal func removeStaleDistinctNotifications654(notificationsofZone: String) {
let notificationsInDB = realm?.objects(Notifications.self)
let onlyGeoNotifsInDB = notificationsInDB?.filter({$0.notification_identifier == notificationsofZone})
if let toBeDeletedGeoNotifs = onlyGeoNotifsInDB?.filter({$0.createdAtTimeStamp < Inventa.shared.insertedTimeStamp}) {
if toBeDeletedGeoNotifs.count > 0 {
do {
try realm?.write {
realm?.delete(toBeDeletedGeoNotifs)
}
} catch {
print(error)
}
}
}
}
Related
I am getting a crash reported in crashlytics about partial apply in closure. I have tried other answers that mainly focus on using [weak self] but that didn't help. However, i am not getting a crash on my device.
According to the report the crash is somewhere in the function where i show my dropDown here is the code
func showDropDown(_ names: [String], forResult result: SearchPatientResultResponnse) {
guard let vc = viewController
else { return }
self.searchedPatientNames = result.data?.patientSearchSuggestions
Helpers.showSearchDropdown(anchorView: vc.searchBar.searchTextField, dataSource: names, scrollToTop: true, completion: { [weak self] (i, item) in
guard let self = self else {
return
}
vc.searchBar.text = item
vc.dismissKeyboard()
self.selectedSearchPatient = self.searchedPatientNames?[i]
if let d = self.searchedPatientNames?[i].dob {
vc.dobTF.text = DateTimeFormatters.userUIDateFormatterInUTC.string(from: d)
}
self.search(self.selectedSearchFilter)
}, fetchPaginationData: { [weak self] in
guard let self = self, !self.isNameSearchLastPage, self.page != -1 else {
return
}
vc.searchBar.isLoadingWithoutSearchIcon = true
self.fetchPatientNameNextPage()
}, cancel: { [weak self] in
self?.resetPaginationParams()
})
}
This is the function from where i am calling this showDropDown function
func getQueryPatientResponse() {
guard let vc = viewController else {
return
}
SocketIOManager.shared.queryResponseForPatient = { [weak self] result in
var names: [String] = []
self?.isNameSearchLastPage = result.data?.isLastPage ?? true
self?.page = result.data?.pageNumber ?? -1
for data in result.data?.patientSearchSuggestions ?? [] {
var name = ""
if !data.middleName.isEmpty {
name = data.firstName + " " + data.middleName + " " + data.lastName
} else {
name = data.firstName + " " + (data.lastName)
}
names.append(name)
}
vc.searchBar.isLoadingWithoutSearchIcon = false
self?.page == 1 ? self?.showDropDown(names, forResult: result) : self?.updateDropDown(names, forResult: result)
}
}
This is the crash report from crashlytics:-
Crashed: com.apple.main-thread
0 Ovada CM - PT 0x639b0 closure #1 in VisitStatusViewModel.showDropDown(_:forResult:)
+ 4340890032 (<compiler-generated>:4340890032)
1 Ovada CM - PT 0x3f328 partial apply for closure #1 in static Helpers.showSearchDropdown(anchorView:dataSource:scrollToTop:completion:fetchPaginationData:cancel:)
+ 121 (Helpers.swift:121)
2 Ovada CM - PT 0x15604c DropDown.tableView(_:didSelectRowAt:)
+ 4341882956 (<compiler-generated>:4341882956)
3 Ovada CM - PT 0x156548 #objc DropDown.tableView(_:didSelectRowAt:)
+ 4341884232 (<compiler-generated>:4341884232)
4 UIKitCore 0xfe36d0 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:isCellMultiSelect:deselectPrevious:]
+ 1640
5 UIKitCore 0xfe3050 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:]
+ 112
6 UIKitCore 0xfe394c -[UITableView _userSelectRowAtPendingSelectionIndexPath:]
+ 316
7 UIKitCore 0x30c240 -[_UIAfterCACommitBlock run] + 64
8 UIKitCore 0x227770 -[_UIAfterCACommitQueue flush] + 200
9 UIKitCore 0x155eb0 _runAfterCACommitDeferredBlocks + 640
10 UIKitCore 0x15657c _cleanUpAfterCAFlushAndRunDeferredBlocks + 128
11 UIKitCore 0x156748 _afterCACommitHandler + 56
12 CoreFoundation 0x3e83c _CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION_ + 32
13 CoreFoundation 0xfa74 __CFRunLoopDoObservers + 616
14 CoreFoundation 0xaffc __CFRunLoopRun + 1012
15 CoreFoundation 0x1e250 CFRunLoopRunSpecific + 572
16 GraphicsServices 0x1988 GSEventRunModal + 160
17 UIKitCore 0x4e5a94 -[UIApplication _run] + 1080
18 UIKitCore 0x27efd4 UIApplicationMain + 336
19 Ovada CM - PT 0x6070 main + 14 (AppDelegate.swift:14)
20 ??? 0x1029dc4d0 (Missing)
I've a random crash in live app. It crashes on guard statement. Following is the code snippet. I'm not able to understand why it crashes on guard which was suppose to guard against crashes like this?
How to fix this issue or how do I go about investigating it?
Crashlytics log
Crashed: com.apple.main-thread
EXC_BREAKPOINT 0x0000000102419850
0 myApp 0x102426f50 MessageVC.validate() + 101 (MessageVC.swift:101)
1 myApp 0x1024272d8 #objc MessageVC.buttonTapped(_:) + 239 (MessageVC.swift:239)
2 UIKitCore 0x1a6a8d9ac <redacted> + 96
3 UIKitCore 0x1a64c3fbc <redacted> + 240
4 UIKitCore 0x1a64c4320 <redacted> + 408
5 UIKitCore 0x1a64c333c <redacted> + 520
6 UIKitCore 0x1a6674a58 <redacted> + 7636
7 CoreFoundation 0x1a2983e68 <redacted> + 32
8 CoreFoundation 0x1a297ed54 <redacted> + 416
9 CoreFoundation 0x1a297f320 <redacted> + 1308
10 CoreFoundation 0x1a297eadc CFRunLoopRunSpecific + 464
11 GraphicsServices 0x1ac91f328 GSEventRunModal + 104
12 UIKitCore 0x1a6a8c63c UIApplicationMain + 1936
13 myApp 0x1023eb850 main + 21 (ProfileVC.swift:11)
14 libdyld.dylib 0x1a2808360 <redacted> + 4
Model.swift
struct ProfileStatus: Decodable {
var status: Bool?
var error: String?
}
MessageVC.swift
var profileStatus: ProfileStatus!
func validate() -> Bool {
guard let status = profileStatus.status else { // Line no. 101, Crash here
return true
}
// Do something...
}
#IBAction func buttonTapped(_ sender: UIButton) {
if validate() { // Line no. 239
// Do something..
}
}
ProfileVC.swift
class ProfileVC: UIViewController {
#IBOutlet weak var textField: MyTextField! // Line no. 11
// ....
}
The reason of crash in force unwrap
var profileStatus: ProfileStatus! // << here is the reason
so you need to find in other code where ownership is lost, and, which is anyway good practice
var profileStatus: ProfileStatus? // use optional and unwrap where needed conditonally
func validate() -> Bool {
guard let status = profileStatus?.status else {
I'm getting a random crash on my live app on Float to Int conversion line.
I can't figure out why it's crashing and can't reproduce it as it's random crash on live app. Any suggestion on how to fix crash?
Crash log
Crashed: com.apple.main-thread
0 MyApp 0x100703778 closure #1 in MyViewController.getBalance(isRefreshed:) + 797 (MyViewController.swift:797)
1 MyApp 0x1005c7670 closure #1 in closure #1 in fetchtBalance(completed:) + 185 (Utils.swift:185)
2 MyApp 0x10051ab10 thunk for #escaping #callee_guaranteed () -> () + 4335790864 (<compiler-generated>:4335790864)
3 libdispatch.dylib 0x1ae908b7c _dispatch_call_block_and_release + 32
4 libdispatch.dylib 0x1ae909fd8 _dispatch_client_callout + 20
5 libdispatch.dylib 0x1ae915cc8 _dispatch_main_queue_callback_4CF + 968
6 CoreFoundation 0x1aebdee0c __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
7 CoreFoundation 0x1aebd9b68 __CFRunLoopRun + 1980
8 CoreFoundation 0x1aebd9084 CFRunLoopRunSpecific + 480
9 GraphicsServices 0x1b8e27534 GSEventRunModal + 108
10 UIKitCore 0x1b2d49670 UIApplicationMain + 1940
11 MyApp 0x1004ec6b8 main + 20 (ClientMyProfileViewController.swift:20)
12 libdyld.dylib 0x1aea58e18 start + 4
Code
import UIKit
var balance: String!
var cost: String?
func getBalance () {
fetchBalance() { (result, error) in
guard let balanceFloatValue = Float(balance!) else {
print("Error")
return
}
guard let costFloat = Float(cost!) else {
print("Error")
return
}
let costPerSec = costFloat / 60
let talkTime = balanceFloatValue / costPerSec
let talkTimeInt = Int(talkTime) // Line No. 797 Crash here
// ....
}
}
The most likely cause for this error is the values themselves
let a:Float = 9999999999999999999999.9
let b = "0.000000000000000000001"
let c:Float = a/Float(b)!
let x = Int(c) // <- Crash here
0/0 will make you crash in: let c:Float = a/Float(b)! so thats not it, but anything else that can make talkTime outside of a Int will make you crash
This would also explain why you only encounter the error randomly since its only for values that make that division NaN or inf or something outside the int like bg2b said
I think you are force unwrapping the balance value. Try to unwrap the converted value like: „Float(balance)!“
I am using JavaScriptCore with multiple threads on iOS 9.3. One JSContext is shared by all the threads. The app crashes sometimes. Does anybody knows what is going on ?
func callFunction(function:String, date:NSDate, dataConfiguration:CDTimePeriodConfiguration, viz:CDViz, didFinish:((response:[String:AnyObject]?, error:NSError?) -> Void)?){
guard let jsonString = self.jsonString(self.apiOptions(date, dataConfiguration: dataConfiguration, viz: viz)) else{
let error = Error.errorWithCode(.ParametersMissing, failureReason: "Cannot create Rocket APIOptions")
didFinish?(response: nil, error: error)
return
}
let randomCallBackFunctionName = "callBackFromJS\(Int64(NSDate().timeIntervalSince1970 * 1000))\(random() % 100000)"
let callBackClosure: #convention(block) (response: [String:AnyObject]?, error: String?) -> Void = {
[weak self]
(response: [String:AnyObject]?, error: String?) -> Void in
var errorMessage:String? = error
if error == "null"{
errorMessage = nil
}
dispatch_async(dispatch_get_main_queue()) {
if let response = response where errorMessage == nil{
didFinish?(response: response, error: nil)
}
else{
if errorMessage == nil && response == nil{
errorMessage = "No reponse from Rocket"
}
let error = Error.errorWithCode(.RocketError, failureReason: errorMessage ?? "Rocket failed for unknown reason")
didFinish?(response: response, error: error)
self?.context.setObject(nil, forKeyedSubscript: randomCallBackFunctionName)
}
}
}
context.setObject(unsafeBitCast(callBackClosure, AnyObject.self), forKeyedSubscript: randomCallBackFunctionName)
let js = "var options = \(jsonString) ; Rocket.\(function)(options).then(function(res) { \(randomCallBackFunctionName)(res, null); }).catch(function(err) { \(randomCallBackFunctionName)(null, err); })"
self.context.evaluateScript(js)
}
0 JavaScriptCore 0x000000018533f3d0 JSC::JSLock::lock(long) + 28
1 JavaScriptCore 0x00000001850453f4 JSC::JSLockHolder::JSLockHolder(JSC::VM&) + 48
2 WebCore 0x0000000185e079a0 WebCore::JSGlobalObjectCallback::call() + 64
3 WebCore 0x0000000185aa3dd8 std::__1::__function::__func<WebCore::Document::postTask(WebCore::ScriptExecutionContext::Task)::$_0, std::__1::allocator<WebCore::Document::postTask(WebCore::ScriptExecutionContext::Task)::$_0>, void ()>::operator()() + 116
4 JavaScriptCore 0x0000000184f35540 WTF::callFunctionObject(void*) + 28
5 JavaScriptCore 0x0000000184f354c0 WTF::dispatchFunctionsFromMainThread() + 240
6 Foundation 0x00000001826a7e20 __NSThreadPerformPerform + 336
7 CoreFoundation 0x0000000181c9cefc __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 20
8 CoreFoundation 0x0000000181c9c990 __CFRunLoopDoSources0 + 536
9 CoreFoundation 0x0000000181c9a690 __CFRunLoopRun + 720
10 CoreFoundation 0x0000000181bc9680 CFRunLoopRunSpecific + 380
11 WebCore 0x0000000185779998 RunWebThread(void*) + 452
12 libsystem_pthread.dylib 0x000000018194fb28 _pthread_body + 152
13 libsystem_pthread.dylib 0x000000018194fa8c _pthread_start + 152
14 libsystem_pthread.dylib 0x000000018194d028 thread_start + 0
Try to call every JSContext related method and functions in one thread:
Create dispatch_queue:
my_queue = dispatch_queue_create("com.example.subsystem.taskXYZ", NULL);
Call methods and functions:
...
// Sync call
dispatch_sync(my_queue) {
...
}
// Async call
dispatch_async(my_queue) {
....
}
I started seeing this error reported on Crashlytics after updating the model in my iOS app (lightweight migration, since the data store is synced via iCloud). The issue seems to affect ~2-3% of all sessions and I found it was very difficult to reproduce in a test environment.
Here is the error (stack trace of the crashing thread):
Thread : Crashed: com.twitter.crashlytics.ios.exception
0 webtv 0x000000010031ad28 CLSProcessRecordAllThreads + 4298337576
1 webtv 0x000000010031ad28 CLSProcessRecordAllThreads + 4298337576
2 webtv 0x000000010031b1d8 CLSProcessRecordAllThreads + 4298338776
3 webtv 0x0000000100305c08 CLSHandler + 4298251272
4 webtv 0x0000000100318f20 __CLSExceptionRecord_block_invoke + 4298329888
5 libdispatch.dylib 0x00000001994c9770 _dispatch_client_callout + 16
6 libdispatch.dylib 0x00000001994d49c4 _dispatch_barrier_sync_f_invoke + 100
7 webtv 0x0000000100318ab8 CLSExceptionRecord + 4298328760
8 webtv 0x00000001003188d0 CLSExceptionRecordNSException + 4298328272
9 webtv 0x0000000100318530 CLSTerminateHandler() + 4298327344
10 libc++abi.dylib 0x0000000198372f44 std::__terminate(void (*)()) + 16
11 libc++abi.dylib 0x0000000198372fd0 std::set_new_handler(void (*)()) + 90
12 libobjc.A.dylib 0x0000000198cdc1a4 _destroyAltHandlerList + 10
13 libdispatch.dylib 0x00000001994c9784 _dispatch_client_callout + 36
14 libdispatch.dylib 0x00000001994d49c4 _dispatch_barrier_sync_f_invoke + 100
15 CoreData 0x0000000183e53b08 -[NSManagedObjectContext performBlockAndWait:] + 252
16 webtv 0x00000001001320ec WTVCoreDataHelper.(executeSync in _B3CAA6076B08D24EA69CA58785DFF9DB)(NSFetchRequest, error : inout NSError?) -> [AnyObject]? (WTVCoreDataHelpers.swift:136)
17 webtv 0x00000001001390f0 WTVCoreDataHelper.defaultProfile() -> WTVProfile? (WTVCoreDataHelpers.swift:529)
18 webtv 0x00000001001335c0 WTVCoreDataHelper.(defaultProfileIfNil in _B3CAA6076B08D24EA69CA58785DFF9DB)(WTVProfile?) -> WTVProfile? (WTVCoreDataHelpers.swift:204)
19 webtv 0x0000000100132de8 WTVCoreDataHelper.(systemFolder in _B3CAA6076B08D24EA69CA58785DFF9DB)(WTVProfile?) -> WTVFolder? (WTVCoreDataHelpers.swift:179)
20 webtv 0x00000001001358a8 WTVCoreDataHelper.homePage(profile : WTVProfile?) -> WTVPage? (WTVCoreDataHelpers.swift:345)
21 webtv 0x0000000100273bec SWWebBrowserViewController.homePageUrl.getter (SWWebBrowserViewController.swift:97)
22 webtv 0x00000001002607f4 SWBrowserHomeButton.evaluateForChangeOfState(NSURL?) -> () (SWBrowserControlButtons.swift:94)
23 webtv 0x000000010025e5b8 SWBrowserControlButton.store(FASFluxStore!, didEmitChangeNotification : NSNotification!) -> () (SWBrowserControlButtons.swift:36)
24 webtv 0x000000010025e630 #objc SWBrowserControlButton.store(FASFluxStore!, didEmitChangeNotification : NSNotification!) -> () (SWBrowserControlButtons.swift)
[...]
49 GraphicsServices 0x000000018ef98088 GSEventRunModal + 180
50 UIKit 0x00000001896caf60 UIApplicationMain + 204
51 webtv 0x00000001002c0c60 main (AppDelegate.swift:19)
52 libdyld.dylib 0x00000001994fa8b8 start + 4
...and here is the iOS thread performing some iCloud transaction logs migration
Thread : com.apple.coredata.ubiquity.entry.pq
0 libsystem_kernel.dylib 0x0000000199608c6c semaphore_wait_trap + 8
1 libdispatch.dylib 0x00000001994da684 _dispatch_semaphore_wait_slow + 244
2 Foundation 0x00000001850fed94 -[NSFileCoordinator(NSPrivate) _blockOnAccessClaim:] + 380
3 Foundation 0x00000001850ff8b0 -[NSFileCoordinator(NSPrivate) _coordinateReadingItemAtURL:options:error:byAccessor:] + 440
4 Foundation 0x00000001850fd8fc -[NSFileCoordinator coordinateReadingItemAtURL:options:error:byAccessor:] + 72
5 CoreData 0x0000000183f23280 -[PFUbiquityFileCoordinator coordinateReadingItemAtLocation:options:retryOnError:error:byAccessor:] + 140
6 CoreData 0x0000000183f3c27c -[PFUbiquityLocation fileExistsAtLocationWithLocalPeerID:error:] + 324
7 CoreData 0x0000000183f77790 -[PFUbiquitySafeSaveFile existsInCloud] + 88
8 CoreData 0x0000000183f4b958 -[PFUbiquityMigrationManager migrateTransactionLogs:andBaselineIfNecessaryForStoreName:peerID:error:] + 1328
9 CoreData 0x0000000183f5db18 -[PFUbiquitySetupAssistant initializeBaselineForStore:error:] + 2576
10 CoreData 0x0000000183f5a3b4 -[PFUbiquitySetupAssistant finishSetupForStore:error:] + 2324
11 CoreData 0x0000000183f59828 -[PFUbiquitySetupAssistant finishSetupWithRetry:] + 152
12 CoreData 0x0000000183f222a8 __57-[PFUbiquitySwitchboardEntry executeBlockOnPrivateQueue:]_block_invoke + 64
13 libdispatch.dylib 0x00000001994c97b0 _dispatch_call_block_and_release + 24
14 libdispatch.dylib 0x00000001994c9770 _dispatch_client_callout + 16
15 libdispatch.dylib 0x00000001994d575c _dispatch_queue_drain + 864
16 libdispatch.dylib 0x00000001994cd274 _dispatch_queue_invoke + 464
17 libdispatch.dylib 0x00000001994c9770 _dispatch_client_callout + 16
18 libdispatch.dylib 0x00000001994d7bb0 _dispatch_root_queue_drain + 2140
19 libdispatch.dylib 0x00000001994d734c _dispatch_worker_thread3 + 112
20 libsystem_pthread.dylib 0x00000001996e9478 _pthread_wqthread + 1092
21 libsystem_pthread.dylib 0x00000001996e9028 start_wqthread + 4
I believe my code follows best practices for core data concurrency (see relevant extracts from the Swift code below). In particular
The managedObjectContext is configured with the PrivateQueueConcurrencyType
All calls to Core Data APIs are wrapped in a managedObjectContext.performBlock()
managedObjectContext is saved and reset in storeWillChange
What am I missing?
Here is the code that crashes
private func executeSync(request: NSFetchRequest) -> [AnyObject]? {
var results: [AnyObject]?
if let moc = managedObjectContext {
moc.performBlockAndWait({ () -> Void in
do {
try results = moc.executeFetchRequest(request) // Crashes here
} catch let error as NSError {
ERROR("ERROR executeFetchRequest of WTVCoreDataHelper threw an error \(error)")
}
})
}
return results
}
Setup of of the persistentStoreCoordinator, managedObjectContext
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("WebVideoCast.sqlite")
var options = [NSObject:AnyObject]()
options[NSPersistentStoreUbiquitousContentNameKey] = kConstants.ubiquityStoreIdentifier
options[NSMigratePersistentStoresAutomaticallyOption] = true
options[NSInferMappingModelAutomaticallyOption] = true
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options)
} catch var error as NSError {
coordinator = nil
var dict = [NSObject:AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: kConstants.errorDomain, code: 9999, userInfo: dict)
ERROR("Unresolved error \(error), \(error.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
// Set the MergePolicy to prioritise external inputs
let mergePolicy = NSMergePolicy(mergeType:NSMergePolicyType.MergeByPropertyStoreTrumpMergePolicyType )
managedObjectContext.mergePolicy = mergePolicy
return managedObjectContext
}()
Relevant delegate methods:
#objc func storeWillChange(notification: NSNotification) {
if let moc = self.managedObjectContext {
moc.performBlockAndWait({ () -> Void in
if moc.hasChanges {
do {
try moc.save()
} catch let error as NSError {
ERROR("ERROR Unresolved error while saving context \(error), \(error.userInfo)")
} catch {
fatalError()
}
}
moc.reset()
})
}
}
Update: I just recently reproduced the problem once on a device where the model had been updated to the latest version - so I am really not sure that the lightweight migration is a contributing factor.