我对块有点困惑。
比如说我有一个带有完成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);
}
}];
}
}];
}
}];
}
}];
}
现在在这里,当所有操作都完成时,我发送的是真的。如果我在第一次成功之后发送true,它会退出整个块还是继续异步运行代码?
答案 0 :(得分:1)
在你的函数中,就是callBack,而不是return.You方法将首先返回。因为代码中有很多异步代码 所以,如果
-(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
答案 1 :(得分:0)
是的,如果您在第一个成功的块中发送StringIndexOutOfBoundsException
,它将退出整个块。