专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构

单例

  • OC 中的单例

      static id instance = nil;
      + (instancetype)sharedManager {
          static dispatch_once_t onceToken;
          NSLog(@"%ld", onceToken);
          dispatch_once(&onceToken, ^{
              instance = [[self alloc] init];
          });
          return instance;
      }
    
      + (instancetype)allocWithZone:(struct _NSZone *)zone {
          static dispatch_once_t onceToken;
          dispatch_once(&onceToken, ^{
              instance = [super allocWithZone:zone];
          });
    
          return instance;
      }
    
      - (id)copyWithZone:(NSZone *)zone {
          return instance;
      }
    
  • Swift 单例
    class HMSoundTool: NSObject {
      // 单例
      static let sharedSoundTools = HMSoundTool()
    }
    
  • OC调用swift 需要#import "单例-Swift.h",其中 单例Product Name
  • Swiftlet 本身就是线程安全的
  • OC 中使用 Swift 的单例

      - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
          NSLog(@"touchesBegan");
          HMNetworkTool *tool = [HMNetworkTool sharedManager];
          NSLog(@"tool = %@", tool);
    
          HMSoundTool *tool2 = [HMSoundTool sharedSoundTools];
          NSLog(@"tool2 = %@", tool2);
      }
    

results matching ""

    No results matching ""