iosobjective-cxcodeipadcore-data

Why does my app hang when breakpoints are disabled?


I have an app that uses several ManagedObjectContexts.

I am using Objective-C.

One MOC is created with NSPrivateQueueConcurrencyType. The rest are created with NSMainQueueConcurrencyType.

I am using [performBlockAndWait:] whenever I work with my MOCs.

When I run my app with breakpoints disabled, the app will hang. The stack trace says that there are 2 threads trying to run performBlockAndWait.

If I run my app with breakpoints enabled and I have several breakpoints that will interrupt my code, the app will not hang.

I have searched online and while I have seen some entries about hangs, nothing has helped nor have I found anything that matches my situation.

I am clearly missing something (or a lot of somethings) in how performBlockAndWait works and when it is or is not appropriate to use.

Very much would like some help/hints. This is very frustrating.

Xcode version is 15.3, deployment target for iOS/iPadOS is 16.4.


Solution

  • performBlockAndWait is an easy source of deadlocks. Many deadlocks are timing-sensitive, so if you add breakpoints, you can completely change the timing and create or avoid deadlocks that may happen in other cases. Even so, the race conditions exist and must be addressed. Your stack trace will show you exactly how this is happening, so start there.

    It is critical that anything in a performBlockAndWait be very simple and not itself rely on any other blocking operations that might re-enter. If your peformBlockAndWait calls any non-trivial method, you need to explore whether that method could also block. Ideally, you should entirely avoid performBlockAndWait and use the simpler perform instead.