Cocoa thread synchronisation when using [ALAssetsLibrary enumerateGroupsWithTypes:]

后端 未结 3 1711
别跟我提以往
别跟我提以往 2020-12-14 23:39

I have recently, like a few people, discovered that [ALAssetsLibrary enumerateGroupsWithTypes] likes to run its blocks on another thread. What a shame that Apple di

3条回答
  •  粉色の甜心
    2020-12-14 23:39

    The answer is to use the NSConditionLock class thusly ...

    typedef enum {
        completed = 0,
        running = 1
    } threadState;
    
    ...
    
    NSConditionLock *lock = [[NSConditionLock alloc] initWithCondition:running];
    

    Then spin off your thread, or in my case a call to [ALAssetsLibrary enumerateGroupsWithTypes:]. Then block the parent thread with this ...

    // Await completion of the worker threads 
    [lock lockWhenCondition:completed];
    [lock unlockWithCondition:completed];
    

    When all work is done in the child/worker thread, unblock the parent with this ...

    // Signal the waiting thread
    [lock lockWhenCondition:running];
    [lock unlockWithCondition:completed];
    

提交回复
热议问题