【问题标题】:How to perform another method after finishing a method using completion block in objective c?在目标c中使用完成块完成方法后如何执行另一种方法?
【发布时间】:2017-01-05 11:20:59
【问题描述】:

我有两种方法。我想在完成第一个任务后执行一个。我怎样才能做到这一点?

【问题讨论】:

  • 放一些代码兄弟
  • 在返回第一个方法完成处理程序之前调用第二个方法
  • @SivajeeBattina 请给我看一些代码,我在完成处理程序方面很弱。
  • func doSomething(flag:Bool, completionHandler:(success:Bool) -> Void) { //这里需要调用你的第二个方法 self.secondMethod() completionHandler(success:true) } func secondMethod(){ }

标签: ios objective-c completion-block


【解决方案1】:

我假设您正在寻找简单的完成块解决方案,所以这应该足够了。

-(void)method1:(void (^ __nullable)(void))completion {
    NSLog(@"method1 started");
    //Do some stuff, then completion
    completion();
    NSLog(@"method1 ended");
}
-(void)method2{
    NSLog(@"method2 called");
}

这样使用,

- (void)viewDidLoad{
    [super viewDidLoad];
    [self method1:^{   //After method1 completion, method2 will be called
        [self method2];
    }];
}

【讨论】:

    【解决方案2】:

    你可以做类似的事情,

        [[manager POST:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
    
                NSLog(@"This is success!!!");
    
           //this is first method's completion blcok!
    
                   // this is another method from completion of first
                        [self saveImages:^(BOOL isDone) {
    
                            // this is second method's completion
    
                        }];
    
                   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
                NSLog(@"failure : Error is : %@",error.localizedDescription);
    
              // this is completion of first method but with failure
    
            }]resume];
    

    这是如何管理它的简单示例!在这我使用了AFNEtworking's 方法,所以不要混淆它!

    【讨论】:

      猜你喜欢
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      相关资源
      最近更新 更多