Delegate和UIActivityIndi​​catorView错误

时间:2016-10-20 14:59:21

标签: ios swift swift3


只是我正在行使委托模式。我创建了一个简单的应用程序,其中委托向 UIViewController 发送消息,说明您是停止还是启动 UIActivityIndi​​catorView 。不幸的是我得到以下错误:错误atal:在展开可选值时意外地发现nil。 似乎 UIActivityIndi​​catorView 未初始化。我无法理解我错在哪里。

    protocol ProgressBarDelegate {
        func UpdateProgressBar(progress: Bool)
    }


    class Dao: NSObject {

        var delegate: ProgressBarDelegate?
        override init() {
            super.init()
           //DELEGATO
            //I who should I send the message? to FirstViewController
            let messaggero = FirstViewController()
            self.delegate = messaggero
            scriviUnMessaggio(progress: true)
        }
 func scriviUnMessaggio(progress: Bool){
        print("I'm writing a message ...")
        delegate?.UpdateProgressBar(progress:progress)      
    }

我的控制器

class FirstViewController: UIViewController,ProgressBarDelegate {

    @IBOutlet  var activity: UIActivityIndicatorView!

    func UpdateProgressBar(progress: Bool){

        print("I received the message from Dao class (the delegate)")

        switch progress{
        case true:
         //   At this point I get the following error:Fatal error: unexpectedly found nil while unwrapping an Optional value


            self.activity.startAnimating()
        case false:
            self.activity.stopAnimating()
        default:
            self.activity.startAnimating()
        } 
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let dao = Dao()

       /// dao.caricamentoDati()

1 个答案:

答案 0 :(得分:1)

问题是您在FirstViewController的init中创建了Dao的新对象。由于FirstViewController对象不是通过xib / storyboard创建的,因此插座未连接。这就是它在self.activity.startAnimating()

发生崩溃的原因

将代理设置为self

中的viewDidLoad

按照以下

更改Doa的init方法
class Dao: NSObject {

  var delegate: ProgressBarDelegate?
    init(delegate: ProgressBarDelegate) {
    super.init()
    //DELEGATO
    //I who should I send the message? to FirstViewController
    self.delegate = delegate
    scriviUnMessaggio(progress: true)
  }
  func scriviUnMessaggio(progress: Bool){
    print("I'm writing a message ...")
    delegate?.UpdateProgressBar(progress:progress)
}

然后在viewDidLoad中执行此操作

override func viewDidLoad() {
  super.viewDidLoad()
  let dao = Dao(delegate: self)
}