单例类的编写

1.自己写

#import "HttpManager.h"

static HttpManager *httpManager=nil;

@implementation HttpManager

+(instancetype )shareManager

{

    //单例对象为空的时候创建

    if (httpManager==nil)

    {

        httpManager=[[HttpManager alloc] init];

    }

    return httpManager;

}

//一般单例类,为防止外界 调用alloc方法,需要重写alloc方法

+ (id)allocWithZone:(struct _NSZone *)zone

{

@synchronized(self)

    {

        if (!httpManager) {

            httpManager=[super allocWithZone:zone];

            return httpManager;

        }

        return httpManager;

    }

}

//重写初始化方法

-(id)init

{

    return httpManager;

}

@end

2.苹果官方建议

Apple官方建议

  由于自己设计单态模式存在一定风险,主要是考虑到可能在多线程情况下会出现的问题,因此苹果官方建议使用以下方式来实现单态模式:

static MyGizmoClass *sharedGizmoManager = nil;

  + (MyGizmoClass*)sharedManager

  {

  @synchronized(self) {

  if (sharedGizmoManager == nil) {

  [[self alloc] init]; // assignment not done here

  }

  }

  return sharedGizmoManager;

  }

  + (id)allocWithZone:(NSZone *)zone

  {

  @synchronized(self) {

  if (sharedGizmoManager == nil) {

  sharedGizmoManager = [super allocWithZone:zone];

  return sharedGizmoManager; // assignment and return on first
allocation

  }

  }

  return nil; //on subsequent allocation attempts return nil

  }

  - (id)copyWithZone:(NSZone *)zone

  {

  return self;

  }

  - (id)retain

  {

  return self;

  }

  - (unsigned)retainCount

  {

  return UINT_MAX; //denotes an object that cannot be released

  }

  - (void)release

  {

  //do nothing

  }

  - (id)autorelease

  {

  return self;

  }

原文地址:https://www.cnblogs.com/fuunnyy/p/4942970.html