sCha
sCha

Reputation: 1504

NotificationCenter inside my own class

I'm trying to set an observer for notifications inside my own class.

Let us say we have something like below for example,

public class MyClass {

  var center: NotificationCenter

  public init() {
    center = NotificationCenter.default
  }

  public run() {
    center.addObserver(self, selector: #selector(test), name: .UIKeyboardDidShow, object: nil)
  }

  func test() {
    Print("TESTED!")
  }
}

and in my ViewController,

override func viewDidLoad() {
  super.viewDidLoad()

  let myClass = MyClass()
  myClass.run()
}

then this actually won't work if I tap textField or something to make the keyboard up.

The NotificationCenter certainly works if I do this without using MyClass, or if I change the object registering as an observer like below:

center.addObserver(ViewController.self, selector: #selector(test), name: .UIKeyboardDidShow, object: nil)

and then of course I should implement my test function inside the ViewController as a class function.

But this isn't the way that I want. Any suggestions or advices that would explain why this isn't working?

Upvotes: 1

Views: 44

Answers (1)

Luan Lai
Luan Lai

Reputation: 483

The myClass will be destroyed at the end of viewDidLoad. Because there is nothing references to it. You should create a property in ViewController:

var myClass: MyClass?

override func viewDidLoad() {
  super.viewDidLoad()

  myClass = MyClass()
  myClass?.run()
}

Upvotes: 2

Related Questions