使iOS块同步执行

Sat*_*hya 21 iphone cocoa-touch ios4 ios objective-c-blocks

如何使块同步执行,或使函数在return语句之前等待处理程序,以便数据可以从块传回?

-(id)performRequest:(id)args
{
__block NSData *data = nil;   

    [xyzclass requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
        data = [NSData dataWithData:responseData];
    }];

    return data;
}
Run Code Online (Sandbox Code Playgroud)

dev*_* gr 27

在这种情况下,您可以使用信号量.

-(id)performRequest:(id)args
{
    __block NSData *data = nil;   
     dispatch_semaphore_t sem = dispatch_semaphore_create(0);
     [xyzclass requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
       data = [NSData dataWithData:responseData];
       dispatch_semaphore_signal(sem);
     }];
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    return data;
}
Run Code Online (Sandbox Code Playgroud)

信号量将阻止执行进一步的语句,直到收到信号,这将确保您的函数不会过早返回.