code

별도의 스레드에서 실행되는 iPhone iOS

codestyles 2020. 8. 26. 07:54
반응형

별도의 스레드에서 실행되는 iPhone iOS


별도의 스레드에서 코드를 실행하는 가장 좋은 방법은 무엇입니까? 그것은 :

[NSThread detachNewThreadSelector: @selector(doStuff) toTarget:self withObject:NULL];

또는:

    NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                        selector:@selector(doStuff:)
                                                                          object:nil;
[queue addOperation:operation];
[operation release];
[queue release];

나는 두 번째 방법을 사용했지만 내가 읽은 Wesley Cookbook은 첫 번째 방법을 사용합니다.


제 생각에 가장 좋은 방법은 GCD (Grand Central Dispatch)라고하는 libdispatch를 사용하는 것입니다. iOS 4 이상으로 제한되지만 너무 간단하고 사용하기 쉽습니다. 백그라운드 스레드에서 일부 처리를 수행 한 다음 주 실행 루프의 결과로 작업을 수행하는 코드는 매우 쉽고 간결합니다.

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Add code here to do background processing
    //
    //
    dispatch_async( dispatch_get_main_queue(), ^{
        // Add code here to update the UI/send notifications based on the
        // results of the background processing
    });
});

아직 수행하지 않았다면 libdispatch / GCD / blocks에서 WWDC 2010의 비디오를 확인하십시오.


iOS에서 멀티 스레딩을위한 가장 좋은 방법은 GCD (Grand Central Dispatch)를 사용하는 것입니다.

//creates a queue.

dispatch_queue_t myQueue = dispatch_queue_create("unique_queue_name", NULL);

dispatch_async(myQueue, ^{
    //stuffs to do in background thread
    dispatch_async(dispatch_get_main_queue(), ^{
    //stuffs to do in foreground thread, mostly UI updates
    });
});

사람들이 게시 한 모든 기술을 시도해보고 어떤 것이 가장 빠른지 확인 하겠지만 이것이 최선의 방법이라고 생각합니다.

[self performSelectorInBackground:@selector(BackgroundMethod) withObject:nil];

NSThread에 카테고리를 추가하여 블록에서 스레드를 쉽게 실행할 수 있습니다. 여기에서 코드를 복사 할 수 있습니다.

https://medium.com/@umairhassanbaig/ios-how-to-perform-a-background-thread-and-main-thread-with-ease-11f5138ba380

참고 URL : https://stackoverflow.com/questions/3869217/iphone-ios-running-in-separate-thread

반응형