aryaxt
aryaxt

Reputation: 77596

Objective C - block question?

I have the following method

+ (NSString*)getMeMyString
{
   NSString *result;
   dispatch_async(dispatch_get_main_queue(), ^{
        result = [ClassNotThreadSafe getString];
    });
   return result;
}

How can i make the block to do it's job synchronously, so that it doesn't return the result before it was retreived?

Upvotes: 1

Views: 654

Answers (3)

Joe
Joe

Reputation: 57169

You are calling dispatch_async which dispatches your block asynchronously. Try using dispatch_sync or dispatch_main if your goal is to block the main thread.

+ (NSString*)getMeMyString
{
   __block NSString *result;
   dispatch_sync(dispatch_get_main_queue(), ^{
        result = [ClassNotThreadSafe getString];
    });
   return result;
}

Grand Central Dispatch Reference

Upvotes: 5

Jose Ibanez
Jose Ibanez

Reputation: 3345

Since it seems like you want to perform a method on a different thread and get a return value, why don't you use an NSInvocation?

SEL theSelector;
NSMethodSignature *aSignature;
NSInvocation *anInvocation;

theSelector = @selector(getString);
aSignature = [ClassNotThreadSafe instanceMethodSignatureForSelector:theSelector];
anInvocation = [NSInvocation invocationWithMethodSignature:aSignature];
[anInvocation setSelector:theSelector];

NSString *result;

[anInvocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:YES];
[anInvocation getReturnValue:result];

Upvotes: 2

CRD
CRD

Reputation: 53000

Use dispatch_sync instead of dispatch_async - then the current thread will be blocked until the block has finished executing on the main thread.

Upvotes: 4

Related Questions