【问题标题】:When do I have to instantiate a class and when I shouldn't? [duplicate]我什么时候必须实例化一个类,什么时候不应该? [复制]
【发布时间】:2016-01-31 21:05:10
【问题描述】:

假设我有一个类let geocoder = CLGeocoder() 的实例。

我现在可以调用geocodeAddressString,这是CLGeocoder 类的一个方法:

geocoder.geocodeAddressString(myObject["Location"] as! String, completionHandler: {
    (placemarks, error) -> Void in
    ...
}

但是,为什么我不能直接执行以下操作?

// I haven't instantiated the `CLGeocoder` class this time
CLGeocoder.geocoder.geocodeAddressString(myObject["Location"] as! String, completionHandler: { (placemarks, error) -> Void in
    ...
})

例如,我可以这样做:

// I don't instantiate the UIView class here
UIView.animateWithDuration(0.4, animations: {
    () in
    ...
}

什么时候必须实例化一个类,什么时候不应该?

【问题讨论】:

标签: swift core-location


【解决方案1】:

在您的第二个示例中,函数“animateWithDuration()”就是我们所说的静态方法,这意味着您可以在不实例化该类的实例的情况下调用它。

在您的第一个示例中,由于您称为“geocoder”的实例实际上不是类中的变量,因此您不能静态调用它。

一般来说,如果要使用静态方法,则不必实例化,但如果要使用非静态方法,则必须使用该类的实例(实例化)版本。

这是面向对象编程的基础。

【讨论】:

  • 感谢 Mapboy! geocodeAddressStringCLGeocoder 类的方法吧?
  • 据我所知,是的。由于它似乎不是静态方法,因此您必须从该类的实例中调用它。
猜你喜欢
  • 2013-10-31
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
相关资源
最近更新 更多