1

我想在 dispatch_group_notify 完成后得到一个布尔值。不幸的是,下面的代码是错误的,我不知道该怎么做......编译器告诉我“不兼容的块指针类型将'BOOL'(^)(void)'传递给'dispatch_block_t'类型的参数(又名' void(^)(void^))" 有什么想法吗?

-(BOOL)saveToDB:(NSArray*)data{

// execute async the saveJSONDictionary
__block BOOL toReturn;
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("saveJsonDictionary", 0);
dispatch_group_async(group, queue, ^{
    for (int i = 0; i < [data count]; ++i) {
        NSDictionary* item = (NSDictionary*)[data objectAtIndex:i];
        [self saveJsonDictionary:item];
    }
    NSManagedObjectContext *moc = [[DatabaseManager sharedManager]managedObjectContext];
    toReturn = [moc save:nil];
});

dispatch_group_notify(group, queue, ^BOOL{
    return toReturn;
});

}

4

2 回答 2

5

First, there is no reason to create a new queue to only dispatch a single block. Toss that block onto one of the existing global queues and be done with it.

Secondly, you'll want to do something like this at the end of that block:

 ....
 BOOL success = [moc save:nil];
 dispatch_async(dispatch_get_main_queue(), ^{
     if (success)
         [someObjectThatCares theSaveIsAllDoneThanksAndComeAgain];
     else
         [someObjectThatCares saveFailedGetOutAndDoNotComeBackUntilYouGetItRight];
 });

That is, no need to use any complex mechanisms. Just add a bit of code at the end of your block that calls some method that can respond to the fact that saving is done.

于 2013-01-16T23:28:06.697 回答
0

The parameter is a block that return void and doesn't accept any parameter, you can't force it to be another type of argument. You have to manually implement a mechanism to get the return value. For example:

dispatch_group_notify(group, queue, ^
{
    [self performSelectorOnMainThread: @selector(notifyValue:) withObject: @(trueOrFalse) waitUntilDone: NO];
});

The method:

- (void) notifyValue: (NSNumber*) value
{
    // You got the "virtual" return value of that method, you can use it.
}
于 2013-01-16T23:25:50.423 回答