I found a lot about Delegates vs Notifications. But I don't really understand the difference yet.
In my project I have a class which is working in the background and update the UI. I have used notifications for that.
Now I created an example: When I click in FirstViewController (FVC) on button1, then the delegate function starts. When I click in FVC on button2, I jump from FVC to the SecondViewController (SVC). I can click button1 many times and someday I click the second button.
But the label in the SVC is always nil.
FVC:
protocol Test {
func someFunction(someString: String)
}
class FirstViewController: UIViewController {
var secViewDel: SecondViewController = SecondViewController()
//...
@IBAction func clickMe(sender: AnyObject) {
secViewDel.myDelegate = self
secViewDel.someFunction("sendAString")
}
override func viewDidLoad() {
super.viewDidLoad()
//do stuff
}
}
SVC:
class SecondViewController: UIViewController,Test {
var myDelegate:FirstViewController? = nil
func someFunction(someString: String) {
print("\(someString)") //sendAString
if let lblNil = lbl {
lblNil.text = someString
} else {
print("lbl is nil") //lbl ist always nil
}
}
@IBOutlet weak var lbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//do stuff
}
}
sendAString
lbl is nil
For sure I can solve my problem in my example, when I use a segue like here. But I don't want always jump to SVC.
A lot of people say that they don't like notification so much. Here I found out that delegates are normally used for 1:1 relations and notifications for 1:n relations. (I find no "official source" for that - does somebody know?)
I would say that in my example it is a 1:1 relation. The FVC could update the SVC x times. Then someday the user jumps to the SVC and see the actual data.
In my project it's a little bit more complicated. There is a class running in the background and get always new data from a server. Everytime when the new data arrives the class updates the main-screen. With notification it works. With delegates I get the same error like in my example: The UI elements are always nil. How can I fix my example?
For me the relation is 1:1 again.
I want to understand in which cases I use delegate or notification.
Thank you