OC写法:(GCD的写法)
.h文件:
#import
@interface AIQueue : NSObject
+ (void)inAISession:(dispatch_block_t)block;
+ (void)cancelOperation;
@end
.m文件:
#import "AIQueue.h"
@interface AIQueue()
@property (nonatomic, strong) dispatch_queue_t sharedQueue;
@end
@implementation AIQueue
static void *dispatchSerialQueueSpecificKey ="test";
+ (instancetype)shared {
static AIQueue*shared =nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
shared = [[self alloc] init];
});
return shared;
}
- (dispatch_queue_t)sharedQueue {
if(_sharedQueue==nil) {
_sharedQueue = dispatch_queue_create(dispatchSerialQueueSpecificKey, DISPATCH_QUEUE_SERIAL);
dispatch_queue_set_specific(_sharedQueue,dispatchSerialQueueSpecificKey, &dispatchSerialQueueSpecificKey, NULL);
}
return _sharedQueue;
}
+ (void)inAISession:(dispatch_block_t)block {
if (dispatch_get_specific(dispatchSerialQueueSpecificKey)) {
block();
}else {
dispatch_async([AIQueue shared].sharedQueue, block);
}
}
@end
OC写法:(NSOperation的写法,带取消功能)
.h文件:
#import
@interfaceAIQueue : NSObject
+ (void)inAISession:(dispatch_block_t)block;
+ (void)cancelOperation;
@end
.m文件:
#import "AIQueue.h"
@interface AIQueue()
@property (nonatomic, strong) NSOperationQueue *sharedQueue;
@end
@implementation AIQueue
static void*dispatchSerialQueueSpecificKey ="test";
+ (instancetype)shared {
static AIQueue*shared =nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
shared = [[self alloc] init];
});
return shared;
}
- (NSOperationQueue *)sharedQueue {
if(_sharedQueue==nil) {
_sharedQueue= [[NSOperationQueue alloc] init];
_sharedQueue.maxConcurrentOperationCount = 1;
}
return _sharedQueue;
}
+ (void)inAISession:(dispatch_block_t)block {
if([NSOperationQueue currentQueue] == [AIQueue shared].sharedQueue) {
block();
}else{
[[AIQueue shared].sharedQueue addOperationWithBlock:block];
}
}
+ (void)cancelOperation {
[[[AIQueue shared] sharedQueue] cancelAllOperations];
}
@end
swift写法:(GCD的写法)
import Foundation
@objcMembers
openclass ARQueue: NSObject {
// 注意此方法为 static
private static var token: DispatchSpecificKey<()> = {
// 初始化一个 key
letkey =DispatchSpecificKey<()>()
// 在主队列上关联一个空元组
return key
}()
public static let openglQueue: DispatchQueue = {
let queue = DispatchQueue.init(label:"test")
queue.setSpecific(key:token,value: ())
return queue
}()
public class func inOpenglSession(_block:@escaping(() ->Void)) {
if DispatchQueue.getSpecific(key:token) !=nil {
block()
}else {
openglQueue.async(execute: block)
}
}
}
网友评论