When I call the following function:
+ (void) myMethod:(NSString *) myConstString array: (NSArray *) myArray
{
dispatch_block_t block =
^{
for (int i = 0; i < myArray.count; i++)
{
if ([@"myString1" isEqual: myConstString])
// Do some easy job here
else if ([@"myString2" isEqual: myConstString])
// Do some other easy job here
[NSThread sleepForTimeInterval: 0.5];
}
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil userInfo:nil];
};
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.example.test", NULL);
dispatch_async(backgroundQueue, block);
}
[[NSNotificationCenter...]
is executed two times. I know that because method in other class which is responsible for "catch" this notification is called two times. First call is instant (and this is strange to me). Second call is after about 2 seconds (this call I like :-) ) I know how to "repair" this:
+ (void) myMethod:(NSString *) myConstString array: (NSArray *) myArray {
dispatch_block_t block =
^{
Boolean isForLoopExecuted = false;
for (int i = 0; i < myArray.count; i++)
{
if ([@"myString1" isEqual: myConstString])
// Do some easy job here
else if ([@"myString2" isEqual: myConstString])
// Do some other easy job here
[NSThread sleepForTimeInterval: 0.5];
isForLoopExecuted = true;
}
if (isForLoopExecuted)
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil userInfo:nil];
};
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.example.test", NULL);
dispatch_async(backgroundQueue, block); }
After addind isForLoopExecuted
everything works propertly. There is only one call after 2 seconds. This suggests that for
loop is not executed when first call is made. I am really curious why this is happening. Thanks for your time!