2017-05-19 11 views
0

그래서 각각은 다음과 같이 수행되도록의 다른 스레드를 분사하는하고 OBJ (-C)를 완료 할 때 다음

-(void)doSomething{ 
    [self expensiveMethod]; 
    [self otherMethod]; //Depends on above method to have finished 
} 

-(void)expensiveMethod{ 
for(int i = 0; i<[someArray count]; i++{ 
    [self costlyOperation:someArray[i]]; 
    } 
} 

가 이상적으로 내가 원하는 나는 다음과 같은 코드가 [self costlyOperation]을 가정 해 봅시다 기다립니다 평행선에 가깝습니다 (물론 이것이 가능하지는 않습니다). [self costlyOperation]이 각 배열 객체에서 처리되면 반환해야하므로 [self otherMethod 처리를 활용할 수 있습니다.

답변

1

기본 대기열을 사용하여 dispatch async를 사용하여 백그라운드에서 작업을 실행할 수 있습니다.

편집

할 수 있습니다 병렬 asyc 실행을위한 그룹 비동기 작업. 요구 사항에 따라 약간 조정해야 할 수도 있습니다.

-(void)doSomething{ 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ 
     //Background Thread 
     [self expensiveMethod:^{ 
      dispatch_async(dispatch_get_main_queue(), ^(void){ 
       //Run UI Updates 
       [self otherMethod]; //Depends on above method to have finished 
      }); 
     }]; 
    }); 
} 

-(void)expensiveMethod:(void (^)(void))callbackBlock { 

    dispatch_group_t group = dispatch_group_create(); 

    for(int i = 0; i<[someArray count]; i++) { 
     __block int index = i; 
     dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^{ 
      [self costlyOperation:someArray[index]]; 
     }); 
    } 

    dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^{ 
     if (callbackBlock) { 
      callbackBlock(); 
     } 
    }); 
} 
+0

그런 종류의 답변이 있습니다. 다른 부분은'expensiveMethod' 내부에 있으며 for 루프 처리를 병렬로 실행하려고합니다. – user1416564

+0

답변을 수정했습니다. – Bilal

+0

감사합니다! 질문 : 가질 수있는 스레드 수에 제한이 있습니까? – user1416564