iOS crash calling rollback on NSManagedObjectContext after resuming from background - ios

I've been bashing my head over this issue for several days now to no avail and have lost all sanity. :|
My app is setup to track the device's location while active and in the background and I'm using CoreData to create and store the track data. The primary CoreData entity is "Route" which has many "RoutePoint" entities. As the device receives a new location from the app's CLLocationManager, a new RoutePoint object is added to its parent Route.
When the user stops tracking, they have the option to save or discard the route. Discarding the route simply calls [_moc rollback], and of course save will call [_moc save]. I'm using the method of referencing my NSManagedObjectContext instance on the AppDelegate rather than a singleton object, which is not being retained nor released in any of my UIViewControllers.
The issue arises if the user sends the app into the background while tracking is active (thus the Route and RoutePoint entities are not actually saved to the _moc). When the app is returned to the active state, the user stops the route chooses to discard it which is when the app crashes (calling "rollback"). However, if the same process is repeated but the user saves the route rather than discarding, there is no crash and it saves successfully. Huh?!
The only thing I get in gdb when this happens is EXC_BAD_ACCESS, so I do a backtrace and here's the result:
#0 0x34a80464 in objc_msgSend ()
#1 0x356ea6d6 in -[_PFManagedObjectReferenceQueue _processReferenceQueue:] ()
#2 0x356ea3d4 in -[NSManagedObjectContext(_NSInternalNotificationHandling) _processReferenceQueue:] ()
#3 0x356ea084 in -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] ()
#4 0x3571fb14 in -[NSManagedObjectContext processPendingChanges] ()
#5 0x357603ee in -[NSManagedObjectContext rollback] ()
#6 0x00031862 in -[RouteHistoryDetailViewController discardRoute] (self=0x4a0fc30, _cmd=0x100941)
#7 0x0003064c in -[RouteHistoryDetailViewController alertView:clickedButtonAtIndex:] (self=0x4a0fc30, _cmd=0x344b7f5f, alertView=0x390aa0, buttonIndex=0)
#8 0x3445d63e in -[UIAlertView(Private) _buttonClicked:] ()
#9 0x35821fec in -[NSObject(NSObject) performSelector:withObject:withObject:] ()
#10 0x341c84ac in -[UIApplication sendAction:to:from:forEvent:] ()
#11 0x341c844c in -[UIApplication sendAction:toTarget:fromSender:forEvent:] ()
#12 0x341c841e in -[UIControl sendAction:to:forEvent:] ()
#13 0x341c8170 in -[UIControl(Internal) _sendActionsForEvents:withEvent:] ()
#14 0x341c89ce in -[UIControl touchesEnded:withEvent:] ()
#15 0x341be354 in -[UIWindow _sendTouchesForEvent:] ()
#16 0x341bdcce in -[UIWindow sendEvent:] ()
#17 0x341a8fc6 in -[UIApplication sendEvent:] ()
#18 0x341a8906 in _UIApplicationHandleEvent ()
#19 0x320c8f02 in PurpleEventCallback ()
#20 0x3580f6fe in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ ()
#21 0x3580f6c2 in __CFRunLoopDoSource1 ()
#22 0x35801f7c in __CFRunLoopRun ()
#23 0x35801c86 in CFRunLoopRunSpecific ()
#24 0x35801b8e in CFRunLoopRunInMode ()
#25 0x320c84aa in GSEventRunModal ()
#26 0x320c8556 in GSEventRun ()
#27 0x341dc328 in -[UIApplication _run] ()
#28 0x341d9e92 in UIApplicationMain ()
#29 0x00002982 in main (argc=1, argv=0x2fdff5a8)
So it appears to be an issue with calling [_moc rollback], but I've done extensive searching and tried various things, even retaining and releasing my MOC instance in that UIViewController, but nothing has worked yet. Clearly something is going awry when the app goes into the background, but it were related to the MOC then wouldn't a similar crash happen when saving as well?
Suggestions are greatly appreciated! :)

I've always just had a flag on my items and performed a save in willResignActive with any "non-confirmed" items having flag=true. Then when I resume (or startup) if I want to discard them, I can delete where flag=true and erase them... that way I can still save or undo even if iOS shuts my app down due to memory pressure.
IIRC Your current design means if someone opens up Safari, etc and your app closes, the route is permanently gone even if the user wants to come back and save it because the changes were only in memory.

Related

Bad Access exception at startup in Xcode 14.0.1 debugger (iOS)

Our iOS app, which was working normally under earlier iOS versions, now has an exception at startup in iOS 16.
Thread 1: EXC_BAD_ACCESS (code=1, address=0x1176aca60)
But this is only visible when debugging; if I run it directly on device, it appears to run fine. Still a problem because we cannot debug our app.
There is very little information available, but this is the call stack, none of which is our code. I stepped through a lot of our startup code without noticing any problems.
Thread 1 Queue : com.apple.main-thread (serial)
#0 0x0000000183aa3518 in objc_release ()
#1 0x0000000183aa15d8 in AutoreleasePoolPage::releaseUntil(objc_object**) ()
#2 0x0000000183aa4f40 in objc_autoreleasePoolPop ()
#3 0x00000001a0061aec in -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] ()
#4 0x00000001a009cd3c in __92-[FBSWorkspaceScenesClient createSceneWithIdentity:parameters:transitionContext:completion:]_block_invoke ()
#5 0x000000010900e04c in _dispatch_client_callout ()
#6 0x0000000109011ac8 in _dispatch_block_invoke_direct ()
#7 0x00000001a006bf2c in FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK ()
#8 0x00000001a006bac8 in -[FBSSerialQueue _targetQueue_performNextIfPossible] ()
#9 0x00000001a006e2a8 in -[FBSSerialQueue _performNextFromRunLoopSource] ()
#10 0x000000018a7be22c in CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION ()
#11 0x000000018a7ca614 in __CFRunLoopDoSource0 ()
#12 0x000000018a74e57c in __CFRunLoopDoSources0 ()
#13 0x000000018a763eb8 in __CFRunLoopRun ()
#14 0x000000018a7691e4 in CFRunLoopRunSpecific ()
#15 0x00000001c3589368 in GSEventRunModal ()
#16 0x000000018cc18d88 in -[UIApplication _run] ()
#17 0x000000018cc189ec in UIApplicationMain ()
#18 0x0000000101d76580 in main at /Users/aaronl/engine-johnsonville/src/platform/ios/main.mm:8
#19 0x00000001a8a8d948 in start ()
Turning on some Xcode debug flags showed the following message:
2022-10-13 16:33:49.020927+1300 umajin_viewer[1297:357539] *** -[CaptureMTLCaptureScope release]: message sent to deallocated instance 0x280aafb40
The app is a combination of Objective-C and C++, and has Vulkan graphics rendering on top of Metal. All this was working well up till now.
I'm looking for any clues on how to find out what is going wrong!
Eventually we were able to confirm that this was a problem in MoltenVK, the implementation of Vulkan on top of Metal for iOS and Mac. It was releasing something that Apple expects to be autoreleased (MTLCaptureScope)? Because it wasn't our code we couldn't see into it. Upgrading to the latest solved this.

Firebase initWithUrl crashes on iOS 5.1

I'm developing a Firebase app to use on my old iPad first generation (iOS 5.1.1). It works fine on the simulator and on other devices but, when I load it on the iPad to test, I receive a crash like this one:
#0 0x33860f86 in objc_msgSend ()
#1 0x33862f94 in objc_retain ()
#2 0x000d26a0 in -[FRepoManager setQueue:] at /Users/mtse/Dev/firebase/firebase-client-objc/Firebase/Firebase/Core/FRepoManager.m:24
#3 0x33fdc5aa in dispatch_once_f$VARIANT$up ()
#4 0x000d1a80 in _dispatch_once [inlined] at /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/usr/include/dispatch/once.h:68
#5 0x000d1a70 in +[FRepoManager singleton] at /Users/mtse/Dev/firebase/firebase-client-objc/Firebase/Firebase/Core/FRepoManager.m:37
#6 0x000e6736 in -[Firebase initWithUrl:] at /Users/mtse/Dev/firebase/firebase-client-objc/Firebase/Firebase/Firebase.m:54
#7 0x000c6f82 in -[AppDelegate application:didFinishLaunchingWithOptions:] at /xxx/AppDelegate.m:25
#8 0x3337acaa in -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] ()
#9 0x333747dc in -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] ()
#10 0x33342ac2 in -[UIApplication handleEvent:withNewEvent:] ()
#11 0x33342566 in -[UIApplication sendEvent:] ()
#12 0x33341f3a in _UIApplicationHandleEvent ()
#13 0x3393422a in PurpleEventCallback ()
#14 0x35c16522 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ ()
#15 0x35c164c4 in __CFRunLoopDoSource1 ()
#16 0x35c15312 in __CFRunLoopRun ()
#17 0x35b984a4 in CFRunLoopRunSpecific ()
#18 0x35b9836c in CFRunLoopRunInMode ()
#19 0x3337386a in -[UIApplication _run] ()
#20 0x33370cd4 in UIApplicationMain ()
#21 0x000c778c in main at /xxx/main.m:14
This happens as soon as the code reaches this line:
Firebase *ref = [[Firebase alloc] initWithUrl:kFirebaseURL];
I tried even downgrading the Firebase framework to older ones but the problem persists. I have the -ObjC linker flag set too. Any ideas of how this can be solved?
Sorry, iOS 5.x is no longer supported by the Firebase SDK. You can try old versions of the SDK to see if one works, but offhand I do not know.
You can fix this by downgrading to v1.0.8 of the framework (direct link to ZIP file) — this is the newest version that doesn't experience this crash on an iPad 1 with iOS 5.1.1.

Keep managedObjectContextDidUnregisterObjectsWithIDs: from blocking main thread

I have an app that performs background fetches to populate entities on a map. The fetch predicate is constantly updating as the user pans and zooms on the map or changes the search filter criteria. The queries take anywhere from a fraction of a second to several seconds to complete. In order to maintain a responsive user experience, I'm performing the fetches on the parent context on a private queue using the built-in main and parent contexts of UIManagedDocument.
I was experiencing blocking on the main thread when things attempted to access the main context, which required accessing the parent context in order to reach the persistent store to fetch faults, etc. I remedied all the affected parts of my own code by pre-fetching relationships and resolving faults before allowing further background fetches on the parent context.
But I am still experiencing blocking of the UI on occasion. When I pause the app during these moments of the UI being unresponsive, I get the following stack traces on the main and private queue threads:
Thread 1Queue : com.apple.main-thread (serial)
#0 0x36a29568 in semaphore_wait_trap ()
#1 0x36ab4558 in _os_semaphore_wait ()
#2 0x0098ff0a in _dispatch_barrier_sync_f_slow ()
#3 0x28a4060c in _perform ()
#4 0x28a4d74e in -[NSManagedObjectContext(_NestedContextSupport) managedObjectContextDidUnregisterObjectsWithIDs:] ()
#5 0x289dc7ae in -[_PFManagedObjectReferenceQueue _processReferenceQueue:] ()
#6 0x289dc012 in _performRunLoopAction ()
#7 0x28c7f624 in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ ()
#8 0x28c7cd08 in __CFRunLoopDoObservers ()
#9 0x28c7d10a in __CFRunLoopRun ()
#10 0x28bca980 in CFRunLoopRunSpecific ()
#11 0x28bca792 in CFRunLoopRunInMode ()
#12 0x2ff7c050 in GSEventRunModal ()
#13 0x2c1bc980 in UIApplicationMain ()
#14 0x0009a070 in main at main.m:17
Thread 288Queue : NSPersistentStoreCoordinator 0x176425c0 (serial)
#0 0x36ab71f8 in _platform_memmove$VARIANT$CortexA9 ()
#1 0x3670ab5e in ___lldb_unnamed_function194$$libsqlite3.dylib ()
#2 0x3670bd4e in ___lldb_unnamed_function195$$libsqlite3.dylib ()
#3 0x366f4cc8 in ___lldb_unnamed_function124$$libsqlite3.dylib ()
#4 0x366f23b4 in sqlite3_step ()
#5 0x289ba75c in _execute ()
#6 0x289ba454 in -[NSSQLiteConnection execute] ()
#7 0x289c77f4 in -[NSSQLCore _newRowsForFetchPlan:selectedBy:withArgument:] ()
#8 0x289c15e0 in -[NSSQLCore newRowsForFetchPlan:] ()
#9 0x289c0bd8 in -[NSSQLCore objectsForFetchRequest:inContext:] ()
#10 0x289c0564 in -[NSSQLCore executeRequest:withContext:error:] ()
#11 0x28a6ce98 in __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke ()
#12 0x28a7411e in gutsOfBlockToNSPersistentStoreCoordinatorPerform ()
#13 0x009889b6 in _dispatch_client_callout ()
#14 0x009901d8 in _dispatch_barrier_sync_f_invoke ()
#15 0x28a67c8e in _perform ()
#16 0x289c01de in -[NSPersistentStoreCoordinator executeRequest:withContext:error:] ()
#17 0x289bee92 in -[NSManagedObjectContext executeFetchRequest:error:] ()
#18 0x000d7f8c in __35-[MainViewController scheduleFetch]_block_invoke at MainViewController.m:1395
#19 0x28a45120 in developerSubmittedBlockToNSManagedObjectContextPerform ()
#20 0x00990e1c in _dispatch_queue_drain ()
#21 0x0098b2f4 in _dispatch_queue_invoke ()
#22 0x00992558 in _dispatch_root_queue_drain ()
#23 0x00993880 in _dispatch_worker_thread3 ()
#24 0x36ab9e24 in _pthread_wqthread ()
Enqueued from com.apple.main-thread (Thread 1)Queue : com.apple.main-thread (serial)
#0 0x0098f852 in _dispatch_barrier_async_f ()
#1 0x0098abd2 in dispatch_async_f ()
#2 0x000d7db4 in -[MainViewController scheduleFetch] at MainViewController.m:1391
#3 0x000d7086 in -[MainViewController setCurrentFetch:] at MainViewController.m:1331
#4 0x000d884a in __35-[MainViewController scheduleFetch]_block_invoke_2 at MainViewController.m:1443
#5 0x009889ca in _dispatch_call_block_and_release ()
#6 0x009889b6 in _dispatch_client_callout ()
#7 0x0098c410 in _dispatch_main_queue_callback_4CF ()
#8 0x28c7ec40 in __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ ()
#9 0x28c7d360 in __CFRunLoopRun ()
#10 0x28bca980 in CFRunLoopRunSpecific ()
#11 0x28bca792 in CFRunLoopRunInMode ()
#12 0x2ff7c050 in GSEventRunModal ()
#13 0x2c1bc980 in UIApplicationMain ()
#14 0x0009a070 in main at main.m:17
#15 0x36977aae in start ()
As you can see, the private queue is busy executing a fetch on the persistent store in sqlite. But the main thread has blocked because [_PFManagedObjectReferenceQueue _processReferenceQueue:] called [NSManagedObjectContext(_NestedContextSupport) managedObjectContextDidUnregisterObjectsWithIDs:], which blocked on a semaphore waiting to access the managed object context I'm assuming. I didn't call this code, but I'd like to know how to avoid it being called and blocking the main thread.
With each new set of NSManagedObjects returned by a query on the background thread, I fetch the objects on the main thread, relative to the main context. Then I place them on the map, first removing the old entities. Once I've done this, I allow the background thread to perform another fetch if one has been queued up from further action by the user.
It seems by the name of the method managedObjectContextDidUnregisterObjectsWithIDs:, this code has something to do with unregistering the entities that I just removed from the map, removing them from memory. Since this must be happening after a new background fetch has begun, is there a way I can expedite this occurring, to delay a new fetch until it does? Or is there a way to prevent it from blocking the main thread when it does happen?
If you are deploying for iOS8, you can take advantage of the new asynchronous fetch API. See the WWDC 2014 talk on Core Data for details.
For details on managedObjectContextDidUnregisterObjectsWithIDs see the documentation for NSIncrementalStore.
If you have to target older versions of iOS, I would suggest abandoning UIManagedDocument, and using MOCs in their raw form.
However, you have to understand that any time you want to access the exact same resource at the same time, there are limitations to what you can do.
In this case, you have a parent context, being busy doing IO, and the child context needs some work done... more importantly, it needs to coordinate with its parent context to do so. This causes your delay.
Without having more information on exactly what you are doing, I can suggest a few alternatives. First, use independent contexts. If you use case requires it, you can also use multiple Core data stacks, including multiple persistent store coordinators.
For high performance tasks, I have had success using a reader stack and a writer stack, with their own complete core data stack, including PSC.

Crash on NSOperation deallocation in NSManagedObjectContext

I am experiencing a problem with CoreData when an NSOperation that download stuff in the background is beeing deallocated.
I am using the nested managed object contexts and the context the operation uses has everything guarded in -[NSManagedObjectContext performBlock:]
However, around the time the operation is beeing deallocated, I get a crash with the following stack:
#0 0x022d9098 in objc_msgSend ()
#1 0x00bfb903 in _PFObjectIDFastHash64 ()
#2 0x029fbdb0 in __CFDictionaryHashKey ()
#3 0x029e13e2 in CFBasicHashFindBucket ()
#4 0x029e0e2d in CFDictionaryGetValue ()
#5 0x00c0a408 in -[NSPersistentStoreCache incrementRefCountForObjectID:] ()
#6 0x00c0a37e in -[NSSQLCore managedObjectContextDidRegisterObjectsWithIDs:] ()
#7 0x00cd378c in -[NSPersistentStoreCoordinator(_NSInternalMethods) _informAffectedStoresOfInterestByChildContextInObjectsWithObjectIDs:withSelector:] ()
#8 0x00c0a29f in -[NSPersistentStoreCoordinator(_NSInternalMethods) managedObjectContextDidRegisterObjectsWithIDs:] ()
#9 0x00cb41db in __95-[NSManagedObjectContext(_NestedContextSupport) managedObjectContextDidRegisterObjectsWithIDs:]_block_invoke_0 ()
#10 0x00c39cc1 in internalBlockToNSManagedObjectContextPerform ()
#11 0x025af014 in _dispatch_client_callout ()
#12 0x0259ed5f in _dispatch_barrier_sync_f_invoke ()
#13 0x0259eaa3 in dispatch_barrier_sync_f ()
#14 0x00c39c8b in _perform ()
#15 0x00c3a6e9 in -[NSManagedObjectContext(_NestedContextSupport) managedObjectContextDidRegisterObjectsWithIDs:] ()
#16 0x00cb41db in __95-[NSManagedObjectContext(_NestedContextSupport) managedObjectContextDidRegisterObjectsWithIDs:]_block_invoke_0 ()
#17 0x00c39cc1 in internalBlockToNSManagedObjectContextPerform ()
#18 0x025a0731 in _dispatch_barrier_sync_f_slow_invoke ()
#19 0x025af014 in _dispatch_client_callout ()
#20 0x0259f7d5 in _dispatch_main_queue_callback_4CF ()
#21 0x02a12af5 in __CFRunLoopRun ()
#22 0x02a11f44 in CFRunLoopRunSpecific ()
#23 0x02a11e1b in CFRunLoopRunInMode ()
#24 0x02dff7e3 in GSEventRunModal ()
#25 0x02dff668 in GSEventRun ()
#26 0x0120bffc in UIApplicationMain ()
#27 0x0000285d in main at /Users/mochs/Projects/12_IP_Lufthansa_Next/Lufthansa/Supporting Files/main.m:16
#28 0x00002785 in start ()
I really have no clue what's going on. What I know is:
I am using ARC
I am using nested managed object contexts
The operation schedules and executes stuff in a shared NSThread with its own runloop
The thread is shared and is not released when the operation is being deallocated
Shortly after -[NSOperation dealloc] the app crashes in the main thread
I fixed the same issue a couple of ours before with a [context reset] in the NSOperation's dealloc method. At this time the concurrency type was NSConfinementConcurrencyType and I didn't use performBlock:
Because of some changes I needed to change the concurrency type of the context to NSPrivateQueueConcurrencyType and make it use performBlock:, now the error is back.
I am pretty sure that the call to reset wasn't really solving the problem but instead just fixing the crash. I have no clue what really leads to such a crash.
Does anybody know what this error is about?
Best regards,
Michael
As far as I know Core Data isn't thread safe. On github you can find these extension that would make Core Data thread safe Adam Roth
Finally I found the issue. When saving all contexts up to the persistent store, is used a method saveToPersistentStore: that I used from RestKit, with some minor changes to match our requirements.
The following line, that should work as a fix on iOS5, caused the issue, at least on iOS6:
[contextToSave obtainPermanentIDsForObjects:[[contextToSave insertedObjects] allObjects] error:&localError];
I have to further investigate wether the issue only occurs on iOS6 (right know, we are not targeting something else) before I send them an issue request, but simply removing this line fixed the issue.

Debugging a EXEC_BAD_ACCESS on iOS

I have a very strange EXEC_BAD_ACCESS error, the error happens on application start.
No breakpoint or NSLog was reached it cancels when
UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])) get called.
It only crashes on simulator not on the device or with instruments.
Zombies give me no informations, when I enable GUARDMALLOC on simulator it doesnt crash.
The EXEC_BAD_ACCESS happens always on the same memory address.
I can get following backtrace
#0 0xcd58a2f6 in ?? ()
#1 0x0102b524 in -[UIWindow _commonInit] ()
#2 0x0102b66f in -[UIWindow initWithFrame:] ()
#3 0x0137be58 in -[UIStatusBarWindow initWithFrame:] ()
#4 0x0103c28f in -[UIView init] ()
#5 0x01000a5e in -[UIApplication _createStatusBarWithRequestedStyle:orientation:hidden:] ()
#6 0x00ffbe6b in -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] ()
#7 0x0100d315 in -[UIApplication handleEvent:withNewEvent:] ()
#8 0x0100e24b in -[UIApplication sendEvent:] ()
#9 0x00fffcf8 in _UIApplicationHandleEvent ()
#10 0x02fe7df9 in _PurpleEventCallback ()
#11 0x02fe7ad0 in PurpleEventCallback ()
#12 0x022cabf5 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ ()
#13 0x022ca962 in __CFRunLoopDoSource1 ()
#14 0x022fbbb6 in __CFRunLoopRun ()
#15 0x022faf44 in CFRunLoopRunSpecific ()
#16 0x022fae1b in CFRunLoopRunInMode ()
#17 0x00ffb7da in -[UIApplication _run] ()
#18 0x00ffd65c in UIApplicationMain ()
#19 0x00002ea2 in main (argc=1, argv=0xbffff2a0) at /Users/user/Projects/App/App/main.m:16
When I try to get informations about the memory I get
Cannot access memory at address 0xcd58a2f6
I can resolve it sometimes when I change some code but it happens again when I only create a local variable in some other functions, so I think the problem lays a bit deeper.
I'm a bit confused because didFinishLaunchingWithOptions never get reached when the error occurs, so what sort of influence can have code in my viewcontrollers?
As 3rd party components I use Phonegap 2.1 as a component and Reachability from Apple.
You can add exception breakpoints to get the location of the error. Here is a nice link of tutorial for the same.
Hope it works for you.
Link is here.
Assuming it is not an xib issue, you could use atos (address to symbol) debugging to help you find the location of the issue.
A good tutorial on this method is available at http://saveme-dot-txt.blogspot.com/2011/04/using-atos-for-reading-crash-logs.html

Resources