NSURLProtocol loading
I’m working on an app that loads a WebView with data using a custom NSURLProtocol and uses CoreData. Tonight I switched the CoreData store from XML, which I use while I’m still playing around with the model, to an SQLite store. Everything looks good until I start changing the selection that feed the WebView its data. I started randomly crashing with the debugger breaking at different points with the following printed:
Iris[2336] An uncaught exception was raised Iris[2336] library routine called out of sequence Iris[2336] *** Uncaught exception: <NSInternalInconsistencyException> library routine called out of sequence
The only thing that the crashes seemed to have in common was that a faulted relationship was trying to be loaded. A quick search of cocoabuilder.com didn’t yield any solutions. So I tried googling “library routine called out of sequence”. A bunch of hits came back showing that it was an SQLite error message and that it is usually caused by a threading issue.
That seemed odd since, to my knowledge, I hadn’t made the app multithreaded yet. I was still doing everything in the main thread. Well, it ends up I was wrong. WebKit spins off threads when loading a WebView and my URL protocol was being called in a background thread. In it I was using the main thread’s NSManagedObjectContext to load the data being displayed. Doing so is fine if everything was running in the same thread, but CoreData doesn’t like threads unless each on has its own NSManagedObjectContext. Creating a new NSManagedObjectContext in the protocol’s class fixed the problem.
So there were two lessons that I can come away with from tonight:
1. If I run into any “library routine called out of sequence” messages I know I have a threading issue with CoreData and need to check what thread and with which NSManagedObjectContext the work is being done.
2. NSURLProtocols are being processed by WebKit in background threads and that I need to watch out for threading issues while writing one.