单例

2016-11-16  本文已影响3人  i诺离

模仿苹果单例实现

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;
}
上一篇 下一篇

猜你喜欢

热点阅读