c# - 具有 NULL 对象的 NSNotificationCenter.PostNotificationName() 不会触发 : bug or as designed?

标签 c# xamarin.ios nsnotificationcenter

我正在使用如下代码订阅我自己的通知:

NSNotificationCenter.DefaultCenter.AddObserver("BL_UIIdleTimerFired", delegate {
    Console.WriteLine("BaseFolderViewController: idle timer fired");
});

发送通知:

NSNotificationCenter.DefaultCenter.PostNotificationName("BL_UIIdleTimerFired", null);

但是,只有当 PostNotificationName(string sString, object anObject) 的“anObject”参数不为 NULL 时,才能正确接收通知。

这是设计使然吗?我必须传递一个对象吗?或者这是一个错误? 我真的不想发送对特定对象的引用。

最佳答案

这是 MonoTouch 中的错误。 NSNotification 的构建使您可以发送一个可选的字典和一个可选的对象,通常是发送者,但也可以是其他对象。这两个都可以为 null,但在 MonoTouch 中将 null 作为对象参数传递会导致空指针异常。

从 iOS 文档中可以清楚地看出,关于 Object 参数: 与通知关联的对象。这通常是发布此通知的对象。可能为零。

public void SendNotification()
{
    NSNotification notification = NSNotification.FromName("AwesomeNotification",new NSObject());            
    NSNotificationCenter.DefaultCenter.PostNotification(notification);
}

public void StartListeningForNotification()
{
    NSString name = new NSString("AwesomeNotification");
    NSNotificationCenter.DefaultCenter.AddObserver(this,new Selector("AwesomeNotificationReceived:"),name,null);            
}

public void StopListeningForNotification()
{
    NSNotificationCenter.DefaultCenter.RemoveObserver(this,"AwesomeNotification",null);             
}

[Export("AwesomeNotificationReceived:")]
public void AwesomeNotificationReceived(NSNotification n)
{

}

关于c# - 具有 NULL 对象的 NSNotificationCenter.PostNotificationName() 不会触发 : bug or as designed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7612166/

相关文章:

ios - Xamarin Studio - Ctrl + 拖动以分配 Root View Controller

iOS - NSNotification 无效选择器

cocoa - 何时创建自定义 NSNotificationCenter?

ios - 如何使用 NSNotificationCenter 调用第二类中的方法?

c# - Linq - 获取根后代

c# - EF6 操作无法完成,因为 DbContext 已被释放

c# - 从 Xamarin.iOS 中的 { alpha, red, green, blue } 值创建 CGColor

ios - 如何将 Xcode View 调试器附加到从 Visual Studio 启动的模拟器?

c# - 将自定义调试信息传递给 Microsoft bot 框架模拟器

c# - 控件上的鼠标按下时间最短