iOS:dispatch\u block\u不能执行部分代码两次,我不知道为什么

iOS:dispatch\u block\u不能执行部分代码两次,我不知道为什么,ios,grand-central-dispatch,nsnotificationcenter,nsthread,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])

当我调用以下函数时:

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

添加后,
isForLoopExecuted
一切正常。2秒后只有一个呼叫。这表明在进行第一次调用时,不会执行for循环。我真的很好奇为什么会这样。谢谢你的时间

首先,每次函数运行时创建新的后台队列可能不是您想要的。您可以拥有的队列数量是有限制的,这是快速达到该限制并崩溃的正确方法。 使用类似以下内容:

调度异步(调度获取全局队列(QOS类实用程序,0),块)

第二,第一个列表没有问题(除了后台队列),它工作正常。通知将只发送一次


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

您是否交叉验证了您没有从代码中的任何其他位置触发相同的通知??添加一个变量来检查执行情况没有意义。如果块被执行,您的通知将被调用。谢谢您的回答。你能解释一下如何调度异步(调度获取全局队列(QOS类实用程序,0),阻塞);works?dispatch\u get\u global\u队列将返回您可以使用的系统后台队列。您只需要指定优先级,在这个示例中,我使用了QOS\u CLASS\u实用程序。我建议在此处查看有关并发编程的文档:
+ (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); }