1、SingletonDemo.h
#import <Foundation/Foundation.h>
@interface SingletonDemo : NSObject
+(instancetype)shareSingletonDemo;//get instance method
@end
2、SingletonDemo.m
#import "SingletonDemo.h"
@implementation SingletonDemo
//静态变量
static SingletonDemo *_instance = nil;
//作用:加载类
//什么时候调用:每次程序一启动,就会把所有的类加载进内存
+(void)load
{
NSLog(@"%s",__func__);
_instance = [[self alloc] init];
}
//get instance
+(instancetype)shareSingletonDemo
{
return _instance;
}
//reload alloc method
+(instancetype)alloc
{
//when the alloc method is being called,if the "_instance" is not nil then raise exception.
if(_instance)
{
NSException* excp = [NSException exceptionWithName:@"NSInternalInconsistencyException"reason:@"There can only be one UIApplication instance" userInfo:nil];
[excp raise];
}
return [super alloc];
}
@end
3、测试代码
//[[SingletonDemo alloc] init];//The wrong way to call singleton instance
SingletonDemo* single = [SingletonDemo shareSingletonDemo];//the right way to call singleton instance
NSLog(@"%@",single);