2012-01-11 97 views
1

我有一个方法返回一个字符串值。 在这种方法中,我有两个调用其他方法。第一个包含一个NSTimer。另一个包含分发通知。 以前的方法修改返回主方法(bgp_result)的字符串变量。 我需要等待包含我的NSTimer的方法才能继续执行,以便在我的主方法中返回正确的值。 所有的方法和变量“bgp_result”在同一个类中。如何等待,直到NSTimer停止

这是我的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; 
} 

回答

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