Objective c++ 如何等待NSTimer停止

Objective c++ 如何等待NSTimer停止,objective-c++,Objective C++,我有一个返回字符串值的方法。 在该方法中,我有两个对其他方法的调用。第一个包含一个NSTimer。另一个包含分布式通知。 前面的方法修改返回main方法(bgp_结果)的字符串变量。 我需要等待包含NSTimer的方法完成,以便继续执行以在我的主方法中返回正确的值。 所有方法以及变量“bgp_result”都在同一个类中 这是我的objective-c++代码 std::string MyProjectAPI::bgp(const std::string& val) {

我有一个返回字符串值的方法。 在该方法中,我有两个对其他方法的调用。第一个包含一个NSTimer。另一个包含分布式通知。 前面的方法修改返回main方法(bgp_结果)的字符串变量。 我需要等待包含NSTimer的方法完成,以便继续执行以在我的主方法中返回正确的值。 所有方法以及变量“bgp_result”都在同一个类中

这是我的objective-c++代码

std::string MyProjectAPI::bgp(const std::string& val)
{       
    FBTest *test = [[FBTest alloc] init];
    NSString *parameters_objc = [NSString stringWithUTF8String:val.c_str()];
    test.parameter_val = parameters_objc;

    // This are the two methods 
    //This method runs the NSTimer. I need to "stop" the execution of the main code until the method launchTimerToCatchResponse finish in order to get an updated value in the variable "bgp_result".
    [test launchTimerToCatchResponse]; 

    [test sendPluginConfirmationNotification];

    const char *bgp_res = [test.bgp_result cStringUsingEncoding:NSUTF8StringEncoding];
    [test release];

    return bgp_res;
}

通常最好使用异步处理程序重写函数,以便调用方可以决定是否要等待,或者是否愿意异步处理结果:

typedef void (^BGPConsumer)(NSString *bgpInfo);

- (void) fetchBGPData: (BGPConsumer) consumer
{
    …
    [self scheduleTimerThatEventuallyCalls:^{
        NSString *info = [self nowWeHaveBGPInfo];
        consumer(info);
    }];
    …
}
如果这不是一个选项,您可以使用信号量阻止执行:

- (void) timesUp
{
    dispatch_semaphore_signal(timerSemaphore);
}

- (void) launchTimerToCatchResponse
{
    [self setTimerSemaphore:dispatch_semaphore_create(0)];
    // …schedule a timer that calls -timesUp after some time
}

- (void) blockedMethod
{
    …
    [self launchTimerToCatchResponse];
    dispatch_semaphore_wait(timerSemaphore);
    dispatch_release(timerSemaphore);
    [self setTimerSemaphore:nil];
    …
}