.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
网友评论