0

나는 다음과 같은 함수를 호출 할 때 :아이폰 OS : dispatch_block_t 알고 코드의 일부를 두 번 실행하고 나는 그나마 왜

+ (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...]가 두 번 실행됩니다. 나는이 통지를 "잡아라"책임이있는 다른 클래스의 메소드가 두 번 호출되기 때문에 그것을 알고있다. 첫 번째 전화는 즉시입니다 (그리고 이것은 나에게 이상합니다).

+ (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 모든 propertly 작동 : 두 번째 통화는 약 2 초 (내가 :-)처럼이 호출) 이후에 I가 "수리"이 방법을 알고있다. 2 초 후에 한 번만 전화가 걸립니다. 이는 첫 번째 호출이 수행 될 때 for 루프가 실행되지 않음을 나타냅니다. 왜 이런 일이 일어나고 있는지 정말 궁금합니다. 시간 내 줘서 고마워!

+0

코드 내의 다른 곳에서 동일한 알림을 보내지 않는다는 확인을 했습니까? 실행을 확인하기 위해 변수를 추가하는 것은 의미가 없습니다. 블록이 실행되는 경우 알림은 어쨌든 호출됩니다. – Gandalf

답변

1

먼저, 함수가 실행될 때마다 새 백그라운드 큐를 만드는 것은 아마도 원하는 것이 아닙니다. 얼마나 많은 대기열을 가질 수 있는지 제한되어 있으며이 제한에 빨리 도달하여 충돌하는 올바른 방법입니다. 다음과 같이 사용하십시오 :

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

두 번째로, 첫 번째 목록에 잘못된 점이 없으며 (백그라운드 대기열 제외) 올바르게 작동합니다. 알림은 한 번만 전송됩니다.

내가 제안하는 것은 정확히 얼마나 많은 횟수로 해당 기능을 실행하는지 알리기 위해 알림을 보낼 때 로그를 저장하는 것입니다. 아마 두 번 이상. 또한 대기열에서 보내는 시간은 전송할 매개 변수에 따라 다릅니다. myArray가 비어 있으면 거의 즉시 알림을받습니다.

+0

답변 해 주셔서 감사합니다. 당신은 어떻게 dispatch_async (dispatch_get_global_queue (QOS_CLASS_UTILITY, 0), 블록); 공장? –

+0

dispatch_get_global_queue는 사용할 수있는 시스템 백그라운드 대기열을 반환합니다. 우선 순위를 지정하기 만하면됩니다.이 예에서는 QOS_CLASS_UTILITY를 사용했습니다. 동시 프로그래밍에 대한 문서를 확인하려면 https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html을 참조하십시오. –