1

i just want to call a method after loading my view. i have set notification to one view and postnotification to other view you will get more idea from my code.. here is my code..

in a one.swift file

override func viewDidLoad() {
            super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "InsertNote:", name: "insert", object: nil)

        }

func InsertNote(notification:NSNotification)
     {
    println("blablalbla")
 }

in a second.swift file

override func viewDidLoad() {
        super.viewDidLoad()
        var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("getData"), userInfo: nil, repeats: false)
    }
    func getData()
    {
    NSNotificationCenter.defaultCenter().postNotificationName("insert", object: nil)
}

i have try also in a dispatch_asynch but still it is not work.

kalpesh
  • 1,285
  • 1
  • 17
  • 30

2 Answers2

0

Try this

let delayInSeconds: Double = 1

override func viewDidLoad() {
    super.viewDidLoad()

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue()){
        NSNotificationCenter.defaultCenter().postNotificationName("insert", object: nil)
    }
}
Yury
  • 6,044
  • 3
  • 19
  • 41
  • He mentioned async not working in a comment on his question. I'm guessing the first VC isn't around to receive the notification. – SpacyRicochet Jun 03 '16 at 12:16
  • no this is not working... if you take a "dispatch_get_global_queue" then it works only in A viewcontroller not in current viewcontroller (B.V.) – kalpesh Jun 08 '16 at 03:35
0

The only reason I can come up with that this doesn't work, is that your first ViewController A is already deallocated when you send the notification with the second ViewController B. So, you are sending the notification with B correctly, but A isn't around to receive it.

You can test this by adding an observer in B as well.

override func viewDidLoad() {
    super.viewDidLoad()
    var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("getData"), userInfo: nil, repeats: false)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "insertNote:", name: "insert", object: nil)
}

func getData() {
    NSNotificationCenter.defaultCenter().postNotificationName("insert", object: nil)
}

func insertNote:(note: NSNotification) {
    print("Banana")
}

// Should print 'Banana' after one second.
SpacyRicochet
  • 2,269
  • 2
  • 24
  • 39
  • i just want to call A viewcontroller method.. because i have so much data in A viewcontroller... – kalpesh Jun 08 '16 at 03:33
  • You should extract all that data and pass it to ViewController B in a simple data object when you present B. A view controller should not ask another view controller for relevant data as a matter of best practices. – SpacyRicochet Jun 08 '16 at 09:59
  • Thank you spacyRicochet.. :) – kalpesh Jun 08 '16 at 10:07