单例的常用写法

#define single_interface(class)  + (class *)shared##class;

#define single_implementation(class) \
static class *_instance; \
 \
+ (class *)shared##class \
{ \
    if (_instance == nil) { \
        _instance = [[self alloc] init]; \
    } \
    return _instance; \
} \
 \
+ (id)allocWithZone:(NSZone *)zone \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [super allocWithZone:zone]; \
    }); \
    return _instance; \
}
View Code

 使用时,直接导入上面的头文件即可.以"single_implementation(类名)"方式声明.以 "shared类名" 方式调用.

 

2.对于类以外的方法,可以用以下代码:

1 static dispatch_queue_t barrage_queue() {
2     static dispatch_queue_t barrage_queue1;
3     static dispatch_once_t onceToken;
4     dispatch_once(&onceToken, ^{
5         barrage_queue1 = dispatch_queue_create("com.pandatv.danmu.operation.queue",  DISPATCH_QUEUE_SERIAL);
6     });
7     return barrage_queue1;
8 };
View Code

 

posted on 2016-09-22 10:32  活最好的自己  阅读(153)  评论(0编辑  收藏  举报

导航