代码之家  ›  专栏  ›  技术社区  ›  youareawaitress

单例和扩展之间的实际区别?

  •  -1
  • youareawaitress  · 技术社区  · 6 年前

    我需要在整个应用程序中共享用户的当前位置,最初我为此创建了一个单例(由位置管理器更新,可在任何地方访问):

    final class CurrentLocation {
    
        static let shared = CurrentLocation()
        var coordinates: CLLocationCoordinate2D?
    
        private init() {}
    
    }
    
    if let currentLocation = CurrentLocation.shared.coordinates {
        //
    }
    

    然后我想扩展 UIDevice 要在不使用singleton的情况下实现相同的效果(由location manager更新并可在任何地方访问):

    extension UIDevice {
    
        static var coordinates: CLLocationCoordinate2D?
    
    }
    
    if let currentLocation = UIDevice.coordinates {
        //
    }
    

    在实际意义上,有什么区别吗?单子通常被看作是伪装的全局变量,但不是扩展,当这样使用时,是同一件事吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   KingHodor    6 年前

    基本上是一样的。在内存管理方面,它们是完全相同的。因为两者分配的大小与内存中的sizeof(cllocationcoordinate2d)相同。但就缓存和CPU而言,扩展比单例好。因为首先必须访问currentlocation对象才能获得坐标。