关于ios中块的混淆
问题描述:
我对块有点混淆。关于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如果我第一个成功发送后,真正到了块它会退出整个块还是继续异步运行代码?
答
在你的函数,即回调,不return.You方法将返回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
+0
非常感谢很多人认真的解释..这清除了我的概念.. – soldiershin
这看起来相当复杂。您应该重新设计代码,以在后台线程中顺序执行这4件事,然后调用完成处理程序。 – Droppy