I am posing a notification and also i am getting the notification and the app works, my app would be working with or without weak self
so I am little confused about using or not using it, maybe some one could help me and show me if i need weak self
and why I need it or why i do not need it here.
This code is for macOS Storyboard Cocoa project.
import Cocoa
import SwiftUI
var appName: String = "My App Name"
class ViewController: NSViewController {
override func viewWillAppear() {
NotificationCenter.default.addObserver(forName: myNotificationName, object: nil, queue: .main) { [weak self] newNotification in
if let unwrappedNewNotification = newNotification.object as? String {
self?.titleUpdater(value: unwrappedNewNotification)
}
}
let controller = NSHostingController(rootView: ContentView())
self.view = controller.view
self.view.window?.title = appName
}
private func titleUpdater(value: String) {
appName = value
self.view.window?.title = value
}
}
struct ContentView: View {
var body: some View {
VStack {
Button("Change", action: {
postMyNotification(value: appName + " updated!")
})
}
.frame(width: 400.0, height: 300.0)
}
}
let myNotificationName: Notification.Name = Notification.Name(rawValue: "myNotificationName")
func postMyNotification(value: String) {
NotificationCenter.default.post(Notification(name: myNotificationName, object: value))
}
Update:
deinit {
if let unwrappedObserver: NSObjectProtocol = observer {
print("worked for deinit!")
NotificationCenter.default.removeObserver(unwrappedObserver)
}
}