Ios 使用块的Objective-c方法

Ios 使用块的Objective-c方法,ios,objective-c,objective-c-blocks,Ios,Objective C,Objective C Blocks,我有一个调用长时间运行的进程的方法。长时间运行的进程和我使用AFNetworking,它本身使用块并返回成功块和失败块。因此,我尝试测试我的方法,在调用success块之前,测试将失败。我想我会尝试让我的方法也使用块。我有另一个方法,我设法更改为使用块,但只使用bool isFinished,返回值为void。我难以处理的方法需要返回NSDecimalNumber*,并使用NSString 方法签名 NSDecimalNumber*getRate:NSString*rateCode; 我希望能够

我有一个调用长时间运行的进程的方法。长时间运行的进程和我使用AFNetworking,它本身使用块并返回成功块和失败块。因此,我尝试测试我的方法,在调用success块之前,测试将失败。我想我会尝试让我的方法也使用块。我有另一个方法,我设法更改为使用块,但只使用bool isFinished,返回值为void。我难以处理的方法需要返回NSDecimalNumber*,并使用NSString

方法签名

NSDecimalNumber*getRate:NSString*rateCode; 我希望能够添加一个带有BOOL的完成块,我在AFNetworking方法进入success块时设置BOOL

我还希望能够调用该方法,并在它的完成块中访问它返回的NSDecimalNumber*值


可能吗?如果是这样,请告诉我您可能需要如何将其拆分

您可以有一个获取完成块的fetchRate:方法:

- (void)fetchRate:(NSString*)rateCode completion:(void (^)(NSDecimalNumber *))completion;
然后这样称呼:

void (^completion)(NSDecimalNumber *) = ^(NSDecimalNumber * rate){
    // this is called when rate is returned from your webservice
}

// call fetchRate: now, results will arrive later...
[ myObj fetchRate:<rate code> completion:completion ];

// code here runs immediately; the results come back later.

这可能有助于不使用get…作为方法的前缀,并将其称为fetchRate或类似的东西,[CurrencyConverter fetchRate:key completion:{}];编译器抱怨syntaxfetchRate标头+无效fetchRate:NSString*速率代码完成:void^NSDecimalNumber*速率完成块;它是类方法还是实例方法?您是对的,我在示例中遗漏了参数名称。它是一个类方法
- (void)fetchRate:(NSString *)rateCode completion:(void (^)(NSDecimalNumber *))completion
{
    void (^asiCompletionBlock)(/*args*/) = ^(/*...args...*/){
        // called after ASI request completes

        NSDecimalNumber * answer = /* get answer from ASI HTTP response */

        // call our completion block that was passed in:
        completion( answer );
    };

    // do your asi HTTP request here, pass asiCompletionBlock for completion arg
}