[OC]Singleton的一种简便实现方式

static dispatch_queue_t xml_request_operation_processing_queue() {
    static dispatch_queue_t af_xml_request_operation_processing_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", DISPATCH_QUEUE_CONCURRENT);
    });

    return af_xml_request_operation_processing_queue;
}

通过dispatch_once执行一次来保证af_xml_request_operation_processing_queue只有一次实例化的机会~

这个方法能够很好的在任何类中调起单例的时候使用~

下面为singleton启一个单独的线程

+ (void) __attribute__((noreturn)) networkRequestThreadEntryPoint:(id)__unused object {
    do {
        @autoreleasepool {
            [[NSThread currentThread] setName:@"AFNetworking"];
            [[NSRunLoop currentRunLoop] run];
        }
    } while (YES);
}

+ (NSThread *)networkRequestThread {
    static NSThread *_networkRequestThread = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
        [_networkRequestThread start];
    });
    
    return _networkRequestThread;
}
 
 
posted @ 2013-05-01 09:52  Eric.wei  阅读(400)  评论(0编辑  收藏  举报