如何等到NSTimer停止

时间:2012-01-11 16:01:55

标签: objective-c++

我有一个返回字符串值的方法。 在那个方法中,我有两个调用其他方法。第一个包含NSTimer。另一个包含分布式通知。 以前的方法修改返回main方法的字符串变量(bgp_result)。 我需要等待包含我的NSTimer的方法完成,以便继续执行以在main方法中返回正确的值。 所有方法都与变量“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;
}

1 个答案:

答案 0 :(得分:0)

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

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];
    …
}
相关问题