How to wait for a thread to finish in Objective-C

前端 未结 7 1984
长情又很酷
长情又很酷 2020-12-23 15:28

I\'m trying to use a method from a class I downloaded somewhere. The method executes in the background while program execution continues. I do not want to allow program exec

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 16:12

    Use an NSOperationQueue, like this
    (from memory so forgive any minor errors -- you'll get the basic idea):

    
    // ivars
    NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
    // count can be anything you like
    [opQueue setMaxConcurrentOperationCount:5];
    
    - (void)main
    {
        [self doStuffInOperations];
    }
    
    // method
    - (void)doStuffInOperations
    {
        // do parallel task A
        [opQueue addOperation:[[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething:) object:@"a"] autorelease]];
    
        // do parallel task B
        [opQueue addOperation:[[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething:) object:@"b"] autorelease]];
    
        // do parallel task C
        [opQueue addOperation:[[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething:) object:@"c"] autorelease]];
    
    
        [opQueue waitUntilAllOperationsHaveFinished];
    
        // now, do stuff that requires A, B, and C to be finished, and they should be finished much faster because they are in parallel.
    }
    
    - (void)doSomething:(id)arg
    {
        // do whatever you want with the arg here 
        // (which is in the background, 
        // because all NSOperations added to NSOperationQueues are.)
    }
    
    
    

提交回复
热议问题