Friday, April 19, 2013

NSThread isMainThread example objc


isMainThread

Returns a Boolean value that indicates whether the receiver is the main thread.
- (BOOL)isMainThread
Return Value
YES if the receiver is the main thread, otherwise NO.

Example - isMainThread

__block NSInteger alertResult; // The __block modifier makes alertResult writable
                               // from a referencing block.
void (^ getResponse)() = ^{
    NSAlert *alert = …;
    alertResult = [NSAlert runModal];
};

if ([NSThread isMainThread]) {
    // We're currently executing on the main thread.
    // We can execute the block directly.
    getResponse();
} else {
    dispatch_sync(dispatch_get_main_queue(), getResponse);
}

// Check the user response.
if (alertResult == …) {
    …
}