Equivalent of GCD serial dispatch queue in iOS 3.x

后端 未结 5 704
日久生厌
日久生厌 2021-01-02 04:52

Apple\'s Grand Central Dispatch (GCD) is great, but only works on iOS 4.0 or greater. Apple\'s documentation says, \"[A] serialized operation queue does not offer quite the

5条回答
  •  青春惊慌失措
    2021-01-02 05:01

    There are things NSOperationQueue documentation writer forgot to mention, making such implementation seem trivial when in fact it's not.

    Setting the maximum concurrent operation count to 1 is guaranteed to be serial only if NSOperations are added to the queue from same thread.

    I'm using another option because it just works.

    Add NSOperations from different threads but use NSCondition to manage queuing. startOperations can (and should, you don't want to block main thread with locks) be called with performSelectorOnBackgroundThread...

    startOperations method represents single job that consists of one or more NSOperations.

    - (void)startOperations
    {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        [[AppDelegate condition] lock];
    
        while (![[[AppDelegate queue] operations] count] <= 0) 
        {
            [[AppDelegate condition] wait];
        }
    
        NSOperation *newOperation = [alloc, init]....;
        [[AppDelegate queue] addOperation:newOperation];
        [[AppDelegate queue] waitUntilAllOperationsAreFinished]; // Don't forget this!
    
        NSOperation *newOperation1 = [alloc, init]....;
        [[AppDelegate queue] addOperation:newOperation1];
        [[AppDelegate queue] waitUntilAllOperationsAreFinished]; // Don't forget this!
    
        NSOperation *newOperation2 = [alloc, init]....;
        [[AppDelegate queue] addOperation:newOperation2];
        [[AppDelegate queue] waitUntilAllOperationsAreFinished]; // Don't forget this!
    
        // Add whatever number operations you need for this single job
    
        [[AppDelegate queue] signal];
        [[AppDelegate queue] unlock];
    
        [NotifyDelegate orWhatever]
    
        [pool drain];
    }
    

    That's it!

提交回复
热议问题