李洪强iOS开发之宏定义方法来初始化一个单例对象
单例的使用:
.m
为了方便实用,只要将以下代码定义在header文件或者.pch文件即可;
// .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; \
}
使用方法:
Manager.h文件
#import <Foundation/Foundation.h>
@interface Manager :NSObject
singleton_interface(Manager);
@end
Manager.m文件
#import "Manager.h"
@interface Manager ()
@end
@implementation Manager
singleton_implementation(Manager)
@end
viewController调用
Manager *manager = [Manager sharedManager];