模仿苹果单例实现
static person *_instance = nil;
+ (void)load
{ // 系统启动的时候,会把所有的类加载进内存(可以理解为系统启动时调用)
_instance = [[self alloc] init];
}
+ (instancetype) sharePerson
{
return _instance;
}
+ (instancetype) alloc
{
if (_instance)
{ //
//name:异常名称
//reason:异常原因
NSException *excp = [NSException exceptionWithName:@"NSInternalInconsistencyException" reason:@"There can only be one UIApplication instance" userInfo:nil];
[excp raise];
}
}
- (id) init
{
if ([super init]){}
return self;
}
- (void)cleanUp{}
工作项目中用到的:
+ (id)sharedInstance
{
static dispatch_once_t pred;
__strong static PrintContext *printContext = nil;
dispatch_once(&pred, ^{
printContext = [[PrintContext alloc] init];
});
return printContext;
}
网友评论