iOS:dispatch_block_t执行两次代码的一部分,我不知道为什么

时间:2014-12-05 09:18:54

标签: ios grand-central-dispatch nsnotificationcenter nsthread

当我调用以下函数时:

+ (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...]执行两次。我知道因为其他班级的方法负责&#34; catch&#34;此通知被调用两次。第一次通话是即时的(这对我来说很奇怪)。第二次通话是在大约2秒后(这个电话我喜欢:-))我知道如何修理&#34;这个:

+ (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); }

在addind isForLoopExecuted之后,一切都有效。 2秒后只有一个电话。这表明在第一次调用时不会执行for循环。我真的很好奇为什么会这样。谢谢你的时间!

1 个答案:

答案 0 :(得分:1)

首先,每次运行该函数时创建新的后台队列可能不是您想要的。您可以拥有多少个队列,这是快速达到该限制并崩溃的正确方法。 使用这样的东西:

dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY,0),block);

其次,首次列出没有任何问题(背景队列除外)并且它可以正常工作。通知只会发送一次。

我建议在发送通知时输入日志,以确切了解执行该功能的次数。可能不止一次。此外,将在队列中花费的时间取决于您在那里发送的参数。如果myArray为空,则几乎立即收到通知。