Xamarin NSNotificatioCenter: How can I get the NSObject being passed?

烂漫一生 提交于 2019-12-03 17:48:10

问题


I am trying to post a notification in a view from my app to another one using NSNotificationCenter. So 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 posting a notification as follows:

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

How can I access the view controller that is being passed in my post notification in my destination class? In iOS it is very straight forward but I cannot seem to find my way in monotouch (Xamarin)...


回答1:


When you AddObserver, you want to do it in a slightly different way. Try the following:

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

and the declaration of your ChangeLeftSide method to conform to Action<NSNotification> expected by AddObserver - giving you the actual NSNotification object. :

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

So when you PostNotificationName, you're attaching the UIViewController object to the notification, which can be retrieved in your NSNotification via the Object property.




回答2:


I found the answer, here are the changes that need to be made on the code 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
}

And the observer is created:

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

Now you can cast or type check the NSObject and do anything with it! Done!



来源:https://stackoverflow.com/questions/15486010/xamarin-nsnotificatiocenter-how-can-i-get-the-nsobject-being-passed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!