I'm facing a strange problem with using NSLog
in iOS's unit test.
The Code
Here is the test code I'm using in my unit test.
- (void)testExample
{
NSOperationQueue *newqueue = [[NSOperationQueue alloc] init];
NSURLRequest *request2 = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.apple.com"]];
dispatch_semaphore_t sema2 = dispatch_semaphore_create(0);
[NSURLConnection sendAsynchronousRequest:request2 queue:newqueue completionHandler:^(NSURLResponse *resp, NSData *data, NSError *error) {
// NSLog(@"2: Data: %@", data);
printf("2: Data: %s\n", [[data description] UTF8String]);
dispatch_semaphore_signal(sema2);
}];
// sleep(2);
dispatch_semaphore_wait(sema2, DISPATCH_TIME_FOREVER);
dispatch_release(sema2);
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.google.com"]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *resp, NSData *data, NSError *error) {
NSLog(@"1: Data: %@", data);
dispatch_semaphore_signal(sema);
}];
// sleep(2);
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);
NSLog(@"Over");
}
To use the code
- Create a simple iOS project with Unit Test.
- Paste the code above to the xxxTest.m
- Press ⌘ + u
Patterns I tried
- Change the order of 2 different urls, for example let
www.google.com
run at first or letwww.apple.com
run at first. - Change the use of
dispatch_semaphore_xxx
tosleep()
. - Change
NSLog()
toprintf()
- Run this code as a Cocoa console app.
- Remove the test of second URL request.
Results
- Running time 0.4s ~ 30s
- Running time 0.4s ~ 30s
- Running time 0.4s ~ 30s
- Running time ~0.4s
- Running time ~0.4s
Questions
- What is happening when I try the first 3 patterns?
- Do you have a similar problem with you?
- Are there any solutions to these?
Thank you guys!