Domanda

On iOS, I am wondering if there is anything akin to the NSZombies flag that can be set to detect/raise when a call is made to an API from a background thread when the main thread is required.

With blocks, it seems to be easy to get into a situation where one either makes false assumptions or mistakes about which thread is doing what. A debugging flag that could detect when a call is made from the wrong thread would be really useful for finding these cases.

It is primarily Apple's frameworks that concern me (Cocoa Touch).

Filed a bug report, #12180446.

È stato utile?

Soluzione

Use the following in any API of yours that requires being on the main thread:

NSAssert([NSThread isMainThread], @"This must only be called on the main thread.");

Apple does not provide such a thing that covers all of UIKit. You will need to call it when you need it.

Altri suggerimenti

I do something more practical. when I call blocks. I do it with a custom method.

+ (void) ensureDispatchOfBlock:(dispatch_block_t) block onQueue:(dispatch_queue_t) queue  async:(BOOL) async{
    if (queue == nil || dispatch_get_current_queue() == queue){
        block();
    }
    else {
        if (async){
            dispatch_async(queue, block);
        }
        else {
            dispatch_sync(queue, block);
        }
    }
}


+ (void) ensureDispatchOnMainThread:(dispatch_block_t) block async:(BOOL) async{
    [self ensureDispatchOfBlock:block onQueue:dispatch_get_main_queue() async:async];
}

This allows me to "Ensure" the dispatch of the block being provided is going to happen on the block it was intended.

Just remember to use async:NO very sparingly.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top