一个共享单例只是一个用类方法容易获得的特定实例,通常存储在一个静态变量中。有很多方法可以实现共享单例,但我的建议是使用Grand Central Dispatch(GCD):

1 + (MYSingleton *)sharedSingleton { 
2   static dispatch_once_t pred; 
3   static MYSingleton *instance = nil; 
4   dispatch_once(&pred, ^{instance = [[self alloc] init];}); 
5   return instance; 
6 }

这样编写方便、速度快,而且线程安全。其他方法要在+sharedSingleton 中添加一个@synchronize 以达到线程安全的目的,但是这种做法在每次调用+sharedSingleton 时都会导致性能显著下降。另外,还可以使用+initialize ,但使用GCD的办法最简单。

相关文章:

  • 2021-08-18
  • 2021-09-26
  • 2021-05-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-25
猜你喜欢
  • 2022-12-23
  • 2021-12-16
  • 2022-12-23
  • 2022-12-23
  • 2021-11-15
  • 2021-07-28
  • 2022-01-18
相关资源
相似解决方案