如何在 Objective-C 中执行完成处理程序

How to execute completition handler in Objective-C

嗨 Whosebug 社区

我有来自 github 项目的以下代码: https://github.com/hybrdthry911/ELStripe 已在此处介绍:

    -(void)createCardFromToken:(NSString *)tokenId customerId:(NSString *)customerId completionHandler:(ELCardCompletionBlock)handler
    {
    [ELStripe executeStripeCloudCodeWithMethod:@"POST" 
        //I use post here because we are creating a card. POST would also be used for updating a customer/card or refunding a charge for example
        prefix:@"customers" //If you look at the documentation and the example URL I use "customers" here as the prefix
        suffix:customerId //The customerID is the suffix, this will be the customer you are going to add the card to
        postfix:@"cards" //I believe this is "sources" now
        secondPostfix:nil //Not needed for this URL
        parameters:@{
            @"card":tokenId  //Only parameter is a tokenId, and I wrap this inside an NSDictionary
        }
        completionHandler:^(id jsonObject, NSError *error) {
                                 if (error)
                                 {
                                     //Handle the error code here

                                     handler(nil,error); //rejectError 
                                     return;
                                 }
                                 //If no error stripe returns a dictionary containing the card information. You can use this information to create a card object if so desired.
                                 handler([ELCard cardFromDictionary:jsonObject],error);
                             }];
    }

我现在的问题是,作为 Objective-C 中的 n00b,我不知道如何使用此方法:

[self createCardFromToken:<#(NSString *)#> customerId:<#(NSString *)#> completionHandler:<#^(ELCard *card, NSError *error)handler#>];

谁能指出我必须在之后添加的内容:completionHandler? 非常感谢!

如果你想知道如何调用这个方法

[self createCardFromToken:@"a token string" customerId:@"a customer id string" completionHandler:^(ELCard *card, NSError *error){
        // here goes code you want to execute when the completion handler gets called
}];

completionHandler 应该是一个块。您可以在这里阅读更多关于它们的信息:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html

最简单的方法是在使用自动完成编写方法时,当 completionHandler 占位符突出显示时按 Enter。它会自动为您编写块骨架。如果您必须手动执行,它应该如下所示:

[self createCardFromToken:@"token value" customerId:@"customer ID" completionHandler:^(ELCard *card, NSError *error) {
    // your custom code that uses card and error values
}];