【问题标题】:How to call second function after first function excecution completed?第一个函数执行完成后如何调用第二个函数?
【发布时间】:2016-03-22 06:42:25
【问题描述】:

我的代码中有 3 个函数。 我为管理队列以执行函数所做的代码。

 [self firstMethodWithOnComplete:^{
    [self SecongMethodWithOnComplete:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(CallThirdMethod) userInfo:nil repeats:NO];
            });
    }];
}];

第一和第二功能

- (void)firstMethodWithOnComplete:(void (^)(void))onComplete {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    //processing here.....

    [self CallFirstMethod];
    onComplete();
});
 }

- (void)SecongMethodWithOnComplete:(void (^)(void))onComplete {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    //processing here.....
    [self CallSecondMethod];
    onComplete();
});
 }

问题是我无法管理他们的执行。我想要这样的执行顺序,即第二个函数仅在第一个结束时执行,第三个在第二次执行结束时执行。 请帮我解决这个问题或提出任何适当的建议。

【问题讨论】:

  • dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"dail image : %@",self.imageUrl); self.imgAppIcon.image = [ UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.imageUrl]]]; }); });
  • 你可以这样试试
  • 阅读这篇文章:stackoverflow.com/questions/7936570/… 它展示了如何调用一个函数(从网站加载数据),然后在完成后调用第二个函数。它显示了如何将函数作为参数传递。这应该为您指明正确的方向。

标签: ios objective-c function


【解决方案1】:

您可以使用调度组来满足这种需求,下面我发布我使用过的示例代码

__block NSError *configError = nil;
__block NSError *preferenceError = nil;

// Create the dispatch group
dispatch_group_t serviceGroup = dispatch_group_create();


dispatch_group_enter(serviceGroup);
 // Start the first async service
dispatch_group_leave(serviceGroup);


dispatch_group_enter(serviceGroup);
// Start the second  async service
dispatch_group_leave(serviceGroup);

dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
    //Update UI in this block of code
});

【讨论】:

  • self.configService和self.preferenceService分别代表什么?
  • 它只是我制作的一个示例功能块,你替换你的代码
  • 上述代码的实现给了我这个错误==> DB Error: database is locked
  • 数据库操作只能在一个线程上完成,或者在主线程上完成
  • 数据库操作在两种方法中,即第一种和第二种,所以我怎样才能把它放到线程中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 2021-08-21
相关资源
最近更新 更多