Creating a method to perform animations and wait for completion using a semaphore in objective c

后端 未结 5 1619
没有蜡笔的小新
没有蜡笔的小新 2020-12-12 01:02

I am trying to create a method which makes use of UIView\'s \"+animateWithDuration:animations:completion\" method to perform animations, and wait for completion. I am well a

5条回答
  •  难免孤独
    2020-12-12 01:23

    As many people pointed out here, is true that the animation runs on the main thread and the semaphore usage stops the main thread. But this still can be done with a semaphore using this approach:

    // create semaphore
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
    
        // do animations
    
    } completion:^(BOOL finished) {
    
         // send signal
        dispatch_semaphore_signal(semaphore);
    
    }];
    
    // create background execution to avoid blocking the main thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
        // wait for the semaphore    
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
        // now create a main thread execution
        dispatch_async(dispatch_get_main_queue(), ^{
    
            // continue main thread logic
    
        });
    
     });
    

提交回复
热议问题