如何在目标c中使用完成块完成方法后执行另一种方法?

时间:2017-01-05 11:20:59

标签: ios objective-c completion-block

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

2 个答案:

答案 0 :(得分:7)

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

-(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];
    }];
}

答案 1 :(得分:1)

你可以做点什么,

    [[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方法,所以不要混淆它!