单例的宏模板

// .h
#define singleton_interface(class) + (instancetype)shared##class;

// .m
#define singleton_implementation(class) \
static class *_instance; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [super allocWithZone:zone]; \
    }); \
\
    return _instance; \
} \
\
+ (instancetype)shared##class \
{ \
    if (_instance == nil) { \
        _instance = [[class alloc] init]; \
    } \
\
    return _instance; \

}


使用:

。h文件

#import <Foundation/Foundation.h>
#import
"Singleton.h"

@interface KRUserInfo : NSObject

singleton_interface(KRUserInfo);

@property (nonatomic,copy) NSString *userName;
@property (nonatomic,copy) NSString *password;

@end


。m文件

@implementation KRUserInfo

//单例实现
singleton_implementation(KRUserInfo);

@end


你可能感兴趣的:(单例,宏)