【问题标题】:Override UIViewController init in Swift 3在 Swift 3 中覆盖 UIViewController 初始化
【发布时间】:2017-05-15 14:34:56
【问题描述】:

在 Objective-C 应用程序中,当从另一个类初始化类时,我对 loadData 进行了一些自定义初始化:

- (id)init {
    self = [super init];
    if (self) {
        [self loadData];
    }
    return self;
}

我需要这个来添加更多数据:

MyViewController *vc = [(MyViewController*)[MyViewController alloc]init];
[vc addMoreData: data]; 

当我尝试将其转换为 Swift 3 时,我对如何做到这一点感到困惑。当我添加 init 方法时,它迫使我添加我不想要的参数(或者我想要吗?)。这也让我添加必需的init(coder:)。如何简单地初始化 ViewController 类并在 ViewController 中覆盖它?

【问题讨论】:

    标签: ios objective-c swift uiviewcontroller swift3


    【解决方案1】:

    在 Swift 中,一个类应该在initializer 方法中初始化所有non-optional 属性,或者non-optional 属性应该具有默认值。

    Swift 编译器强制为符合NSCoding 协议的类添加init?(coder:)

    class MyViewController :UIViewController {
    
    var helpText :String = "" //non-optional property with default value
    var data :AnyObject? //Its an optional property, it has nil value by default
    
    init() {
    
        //initalize all the properties of MyViewController here, before calling super class designated initalizer
    
        super.init(nibName: "MyViewController", bundle: nil)//Designated initializer, pass nil, for both params if not using NIB
    
        //Now you have access to self
        self.loadData(data: nil)
    
    }
    
    
    
    //This method needs to be implemented as UIViewController conform to NSCoding protocol
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func loadData(data :AnyObject?) {
        //Your own implementation
    }
    
    func addMoreData(data :AnyObject?) {
        //Your own implementation
    }
    
    }
    

    用法:

    let myViewController = MyViewController()
    myViewController.addMoreData(data: nil) //pass your data here
    

    阅读代码 sn-p 中的 cmets,希望这能回答您的问题!

    【讨论】:

      【解决方案2】:

      你可以这样做:

      class MyViewController : UIViewController {
      
          required init?(coder aDecoder: NSCoder) {
      
          }
      
          override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
              super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
              loadData()
          }
      }
      

      然后像这样初始化viewController:

      let vc = MyViewController(nibName: "MyViewController", bundle: Bundle.main)
      vc.addMoreData(data)
      

      希望对你有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-24
        • 2014-11-10
        • 1970-01-01
        • 2016-07-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多