Xamarin NSNotificatioCenter:我怎样才能通过NSObject?

P. *_*ami 9 c# xamarin.ios nsnotificationcenter ipad

我正在尝试使用NSNotificationCenter在我的应用程序中向另一个应用程序发布通知.所以在我的目标类中,我创建我的观察者如下:

NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", delegate {ChangeLeftSide(null);});
Run Code Online (Sandbox Code Playgroud)

我有我的方法:

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

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

NSNotificationCenter.DefaultCenter.PostNotificationName("ChangeLeftSide", this);
Run Code Online (Sandbox Code Playgroud)

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

Luk*_*uke 8

当你AddObserver,你想以稍微不同的方式做到这一点.请尝试以下方法:

NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", ChangeLeftSide);
Run Code Online (Sandbox Code Playgroud)

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

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

所以,当你PostNotificationName,你将UIViewController对象附加到通知,可以NSNotification通过Object属性检索通知.


P. *_*ami 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
}
Run Code Online (Sandbox Code Playgroud)

观察者被创建:

NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", ChangeLeftSide);
Run Code Online (Sandbox Code Playgroud)

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

  • 有趣的是,你花了一年的时间才找到下面发布的答案:) (3认同)