关于 ios 中的块的混淆

Confusion regarding blocks in ios

我对块有点困惑。

举例来说,我有一个完成 BOOL 的块:

-(void) addNewSubGoalToLocalDatabaseAndParse:(CompletionBlock )cb
{
    SubGoal* subGoalToAdd = [SubGoal new];
    subGoalToAdd.name = subGoalName;
    subGoalToAdd.parentGoal = goal;
    Score* scoreToAdd = [Score new];
    scoreToAdd.score = 0;
    scoreToAdd.subgoal = subGoalToAdd;
    [subGoalToAdd pinInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if (succeeded) {
        [scoreToAdd pinInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
            if (succeeded) {
                NSLog(@"NEW SUBGOALS AND SCORES ADDED");
                [subGoalToAdd saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        [scoreToAdd saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                            if (succeeded) {
                                NSLog(@"NEW SUBGOALS AND SCORES ADDED");
                                cb(true);
                            }
                        }];
                    }
                }];
            }
        }];
    }
}];
}

现在,当所有操作都是 completed.Say 时,我向块发送 true 如果我在第一次成功后向块发送 true,它会退出整个块还是继续 运行异步编码?

是的,如果您在第一个成功的块中发送cb(true);,它将退出整个块。

在您的函数中,即回调,而不是 return.You 方法将 return first.Because 您的代码中有很多异步代码 所以,如果

-(void) addNewSubGoalToLocalDatabaseAndParse:(CompletionBlock )cb
{
SubGoal* subGoalToAdd = [SubGoal new];
subGoalToAdd.name = subGoalName;
subGoalToAdd.parentGoal = goal;
Score* scoreToAdd = [Score new];
scoreToAdd.score = 0;
scoreToAdd.subgoal = subGoalToAdd;
[subGoalToAdd pinInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (succeeded) {
    cb(true);
    [scoreToAdd pinInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
        if (succeeded) {
            NSLog(@"NEW SUBGOALS AND SCORES ADDED");
            [subGoalToAdd saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    [scoreToAdd saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            NSLog(@"NEW SUBGOALS AND SCORES ADDED");
                            cb(true);
                        }
                    }];
                }
            }];
        }
    }];
}
}];
}

您将有两个回调。

我用那些代码测试

-(void)testFunction:(CALLBACK)callback{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    sleep(2);
    callback(@"1");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(2);
        callback(@"2");
    });

});
}

然后打电话

 [self testFunction:^(NSString *str) {
    NSLog(@"%@",str);
}];

这将输出

2015-05-29 15:57:24.945 OCTest[5009:261291] 1
2015-05-29 15:57:26.950 OCTest[5009:261291] 2