我正在使用如下代码订阅我自己的通知:
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/