2013-03-18 18 views
7

我想从我的应用程序发布通知到另一个使用NSNotificationCenter的视图。所以在我的目的地类创建我的观察如下:Xamarin NSNotificatioCenter:我怎样才能让NSObject通过?

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

,我有我的方法:

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

现在我发布一个通知如下:

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

如何访问正在我的发布通知中传递到目标类中的视图控制器?在iOS中它是非常直接的,但我似乎无法找到我的方式monotouch(Xamarin)...

回答

0

我找到了答案,在这里是需要在我张贴的问题的代码所做的更改:

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 
} 

和观察者创建:

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

现在你可以强制转型或者类型检查NSObject,并用它做任何事情!完成!

+1

只是有趣的你花了一年的时间找到下面发布的答案:) – Injectios 2016-04-18 13:01:54

6

当你AddObserver,你想要以一个稍微不同的方式做到这一点。请尝试以下操作:

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

和你ChangeLeftSide方法的声明符合Action<NSNotification>AddObserver预期 - 给你的实际NSNotification对象。 :

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

所以,当你PostNotificationName,您要附加的的UIViewController对象的通知,您也可以在NSNotification通过Object属性检索。

+0

啊大便,没有看到你的编辑。 – Luke 2013-03-18 20:50:26

+0

谢谢,虽然:)肯定你有比我更好的措辞! – 2013-03-18 21:08:07