Grand Central Dispatch and unit testing

北慕城南 提交于 2019-12-22 00:29:39

问题


I have written a simple test case that follows Apple's documentation and I am not seeing the results that I'm expecting.

Here's the code:

- (void)testExample2
{
    NSLog(@"1");

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); 

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"3");
             dispatch_semaphore_signal(semaphore);
        });

    NSLog(@"2");
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    NSLog(@"4");    
    dispatch_release(semaphore);    
}

I would expect to read: 1, 2, 3, 4 but instead my console just shows me 1, 3.

I've been able to work around the issue using DISPATCH_TIME_NOW in a while loop together with a NSLoop hack but the code above should kind of work... right?

Cheers...

UPDATE

I just realised that I should be using a separate queue rather than dispatch_main_queue()


回答1:


Ended up doing the following in my tearDown.

while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
    NSLog(@"...Tearing Down Tests..");
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                             beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
}
dispatch_release(semaphore);  

and pushing the semaphore creation into the setUp.



来源:https://stackoverflow.com/questions/10733978/grand-central-dispatch-and-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!