SynthesizeSingleton.h,Object-c单例宏

来源:互联网 发布:女生百搭外套 知乎 编辑:程序博客网 时间:2024/05/29 18:42

 //

//  SynthesizeSingleton.h
//  CocoaWithLove
//
//  Created by Matt Gallagher on 20/10/08.
//  Copyright 2009 Matt Gallagher. All rights reserved.
//
//  Permission is given to use this source code file without charge in any
//  project, commercial or otherwise, entirely at your risk, with the condition
//  that any redistribution (in part or whole) of source code must retain
//  this copyright and permission notice. Attribution in compiled projects is
//  appreciated but not required.
//

#define SYNTHESIZE_SINGLETON_FOR_HEADER(className) \
\
+ (className *)shared##className;

#define SYNTHESIZE_SINGLETON_FOR_CLASS(className) \
\
+ (className *)shared##className { \
static className *shared##className = nil; \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
shared##className = [[self alloc] init]; \
}); \
return shared##className; \
}


#define SYNTHESIZE_SINGLETON_FOR_CLASS_INITMETHODS(className) \
\
+ (className *)shared##className { \
static className *shared##className = nil; \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
shared##className = [[self alloc] init]; \
[shared##className initConfig];\
}); \
return shared##className; \
}

以上为SynthesizeSingleton.h内容。

使用方法:(1)在类的h文件中添加 SYNTHESIZE_SINGLETON_FOR_HEADER(单例类)

(2)在类的m文件中添加  SYNTHESIZE_SINGLETON_FOR_CLASS_INITMETHODS(单例类);

(3)这样这个类就成为单例类,调用时直接使用[### shared###];

0 0