Xamarin NSNotificatioCenter: How can I pass an NSObject?

I am trying to post a notification in a view from my application to another using NSNotificationCenter. Therefore, in my destination class, I create my observer as follows:

NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", delegate {ChangeLeftSide(null);}); 

and I have my method:

 public void ChangeLeftSide (UIViewController vc) { Console.WriteLine ("Change left side is being called"); } 

Now from another UIViewController I am sending a notification as follows:

 NSNotificationCenter.DefaultCenter.PostNotificationName("ChangeLeftSide", this); 

How can I access the view controller that is sent in my mail notification in my target class? In iOS, this is very straight forward, but I can not find my way in monotouch (Xamarin) ...

+7
source share
2 answers

I found the answer, here are the changes that need to be made to the code that I posted in the question:

 public void ChangeLeftSide (NSNotification notification) { Console.WriteLine ("Change left side is being called"); NSObject myObject = notification.Object; // here you can do whatever operation you need to do on the object } 

An observer is created:

 NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", ChangeLeftSide); 

Now you can quit or enter NSObject validation and do something with it! Done!

0
source

When you are AddObserver , you want to do it a little differently. Try the following:

 NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", ChangeLeftSide); 

and declaring your ChangeLeftSide method to match the Action<NSNotification> expected by AddObserver - providing the actual NSNotification object.

 public void ChangeLeftSide(NSNotification notification) { Console.WriteLine("Change left side is being called by " + notification.Object.ToString()); } 

So, when you are PostNotificationName , you attach the UIViewController object to the notification, which can be found in your NSNotification using the Object property.

+6
source

All Articles