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