iOS 单例的创建

Objective-C创建单例

+ (Manager *)sharedManager {
  static Manager *sharedManager = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedManager = [[Manager alloc] init];
  })
  return sharedManager;
}

Swift创建单例

class Manager {
  static let shared = Manager()
  private init() {}
}
确保唯一性

复写allocWithZone、copyWithZone、mutablecopyWithZone,避免通过alloc init、copy方式创建单例对象。

+ (id)allocWithZone:(struct _NSZone *)zone
{
    return [Manager sharedManager] ;
}
 
- (id)copyWithZone:(NSZone *)zone
{
    return [Manager sharedManager] ;
}
 
- (id)mutablecopyWithZone:(NSZone *)zone
{
    return [Manager sharedManager] ;
}

你可能感兴趣的:(iOS 单例的创建)