在Swift中,未来的新API将在App Store的现有应用程序中被用户定义的方法覆盖吗?

use*_*er_ 5 iphone xcode objective-c ios swift

例如,在Objective-C中,如果Apple添加了一个名为method1UIView的新方法,那么已经发布到App Store并使用以下代码的现有应用程序可能会崩溃或出现意外行为:

// Objective-C
@interface MyView : UIView
- (void)method1;
@end

// Swift
class MyView : UIView {
    func method1() {
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)


但是在Swift中,要覆盖一个方法,你需要一个override关键字来防止意外覆盖.如果覆盖不带override关键字的方法,编译器将生成编译时错误.

如果Apple在下一个iOS版本中添加新的API方法,并且我的应用程序或您的应用程序使用的名称与新API名称相同的方法,将会发生什么.

在Swift中,现有应用程序(如Objective-C)中的方法是否会覆盖新的API方法?
或者,由于Swift的显式覆盖功能(override关键字),新的API不会影响现有的同名用户定义方法?

S.H*_*.H. 1

如果您的应用程序已经构建并上传,则不会有问题。

但是,如果您尝试为新的更新重新构建应用程序,但运气不好,他们将新的 Api 方法命名为与您的对象方法相同的名称,那么您很可能仅在使用该方法的地方遇到错误您没有使用正确的标识符,例如不调用 self.method1() 而是仅调用 method1() ,并且您的对象继承自 UIViewController,而 UIViewController 恰好具有新的 Method1。

除此之外,我不会担心发生此类问题,至少在我为 iOS 编程的 3-4 年里没有遇到过这样的问题。

//Lets assume UIViewController has a new Method in the Api now which 
//they updated called   Method1

class MyViewController :UIViewController {


  init {
     //When you try to re-build your app this line of code right here would complain
     //because of ambiguity, two methods called the same one from your 
     //Parent Class and your own Class.
     //method1()

     //"super.method1()"  or code below to solve the ambiguity issue.
     self.method1()
  }

//Added this just because I happen to use UIViewController.
 override viewDidLoad() {
     super.viewDidLoad()
 }




  //Your own method without Override, since you want to use your own method. 
  func method1() {
    //Does something important
  }


}
Run Code Online (Sandbox Code Playgroud)

根据您的评论更新:

1)有关于它的文档吗?或者你自己在 Swift 中测试过它吗?

我自己测试过,因为我在App Store中有应用程序。因此,无论已上传什么,代码都将正常工作,因为您上传的应用程序将框架及其当前工作的 API 和您的类预先打包。不,我还没有看到关于它的文档,我知道它是因为我亲自看到过它。

2)我认为如果 UIViewController 已经有 func method1() 的话,你就不能在没有 override 关键字的情况下定义 func method1()

没错!假设 APi 已经有一个方法,您可以使用 write Override 关键字来使用该同名函数。但请记住,根据您提到的场景,API 在您将项目上传到 AppStore 后创建了具有该名称的方法。因此,只有在进行一些新编码并尝试重建应用程序时,您才会看到它。