美文网首页
RunLoop的实际运用

RunLoop的实际运用

作者: 御雪飞斐 | 来源:发表于2019-03-26 14:51 被阅读0次

    .h代码:

    #import <Foundation/Foundation.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    __attribute__((objc_subclassing_restricted))
    @interface RLTransaction : NSObject
    
    + (void)commitAction:(void (^)(void))action;
    
    @end
    
    NS_ASSUME_NONNULL_END
    

    .m代码:

    #import "RLTransaction.h"
    
    
    @interface RLTransaction ()
    @property (nonatomic, copy) void (^action)(void);
    @end
    
    
    static NSMutableArray *g_transactionArray = nil;
    static dispatch_queue_t g_actionQueue = nil;
    
    static void RLTransactionSetup()
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            g_transactionArray = @[].mutableCopy;
            g_actionQueue = dispatch_queue_create("action_queue", NULL);
            CFRunLoopRef runloop = CFRunLoopGetMain();
            CFRunLoopObserverRef observer;
            
            observer = CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(),
                                                          kCFRunLoopBeforeWaiting | kCFRunLoopExit,
                                                          true,
                                                          0xFFFFFF,
                                                          ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity)
            {
              if (g_transactionArray.count == 0)
                  return;
              
                dispatch_sync(g_actionQueue, ^{
                    NSArray *tasks = g_transactionArray.copy;
                    [g_transactionArray removeAllObjects];
                    
                    [tasks enumerateObjectsUsingBlock:^(RLTransaction *obj, NSUInteger idx, BOOL * stop) {
                        obj.action();
                    }];
                });
            });
            
            CFRunLoopAddObserver(runloop, observer, kCFRunLoopCommonModes);
            CFRelease(observer);
        });
    }
    
    
    @implementation RLTransaction
    
    + (void)commitAction:(void (^)(void))action
    {
        RLTransaction *transaction =  [RLTransaction new];
        transaction.action = action;
        RLTransactionSetup();
        [g_transactionArray addObject:transaction];
    }
    
    @end
    
    

    相关文章

      网友评论

          本文标题:RunLoop的实际运用

          本文链接:https://www.haomeiwen.com/subject/ncigvqtx.html