Alterplay/APAddressBook — pull request #9 by monowerker (2014-06-03 10:46:02+00:00)
Title: Fix intermittent crashing in requestAccessWithCompletion-handler

Thread 10 Crashed:
0 libsqlite3.dylib 0x000000018ffaaf60 sqlite3_value_text + 3384
1 libsqlite3.dylib 0x000000018ff9d92c sqlite3_step + 4780
2 libsqlite3.dylib 0x000000018ff9c858 sqlite3_step + 472
3 AppSupport 0x0000000187b9d264 CPSqliteStatementSendResults + 84
4 AppSupport 0x0000000187ba2ee8 CPRecordStoreProcessRecordStatementWithPropertyIndices + 196
5 AppSupport 0x0000000187ba3258 CPRecordStoreProcessQueryWithBindBlock + 136
6 AppSupport 0x0000000187ba3314 CPRecordStoreCopyAllInstancesOfClassWhereWithBindBlock + 136
7 AddressBook 0x0000000182bb89c8 ABCCopyArrayOfAllPeopleInSourceWithSortOrdering + 84
8 Mobilimeet 0x000000010037b9e0 __48-[APAddressBook loadContactsOnQueue:completion:]_block_invoke (APAddressBook.m:82)
9 AddressBook 0x0000000182c0a728 __37-[ABTCC accessRequestWithCompletion:]_block_invoke + 44
10 libdispatch.dylib 0x0000000190244014 _dispatch_call_block_and_release + 20
11 libdispatch.dylib 0x0000000190243fd4 _dispatch_client_callout + 12
12 libdispatch.dylib 0x000000019024b2b8 _dispatch_root_queue_drain + 552
13 libdispatch.dylib 0x000000019024b4fc _dispatch_worker_thread2 + 72
14 libsystem_pthread.dylib 0x00000001903d96bc _pthread_wqthread + 352
15 libsystem_pthread.dylib 0x00000001903d954c start_wqthread + 0

The completion handler is called on an arbitrary thread, but accessing the same address book instance need to be serialized to one thread, see Apple documentation reference below. In practice I've only seen crashes here when using the -loadContacts: API that is in it's turn using -loadContactsOnQueue:completion suppling the main queue as the queue argument.

So, since requestAccessWithCompletion is called on the main thread we dispatch_async to the main queue for the ABAddressBookCopyOfAllPeople call and then another dispatch_async to the queue supplied for execution of the API-consumers completionBlock.

Reading:
* https://developer.apple.com/library/ios/documentation/AddressBook/Reference/ABAddressBookRef_iPhoneOS/Reference/reference.html#//apple_ref/c/func/ABAddressBookRequestAccessWithCompletion
* http://alxsrg.com/?p=190