2011-02-03 70 views
2

我有一个辅助方法,它可以加密iPhone上的一些数据。如果操作因设备被锁定而中断,我想删除刚处理的文件。因此,如果调用该方法,我添加一个通知列表器。尝试聆听NSNotification时如何停止观察?“Obsolete”警告?

两个问题: 1.我收到警告,说我用来添加侦听器的方法已过时。我还能怎么做呢? 2.如果处理完成,我想摆脱听众 - 但如何?

private static foo(string sDestPathAndFile) 
{ 
    NSNotificationCenter.DefaultCenter.AddObserver ("UIApplicationProtectedDataWillBecomeUnavailable", 
    delegate(NSNotification oNotification) 
    { 
    Util.DeleteFile (sDestPathAndFile); 
    throw new InvalidOperationException ("Protected data became unavailable - device locked?"); 
    }); 

    // Do some processing here. 
    // ... 
    // Now get rid of the notification listener - but how? 
} 

回答

2

为了摆脱过时的警告,你应该使用下列内容:

NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.ProtectedDataWillBecomeUnavailable, Handler); 

这适用于所有观察者,例如:

UIKeyboard.WillHideNotification 
UIKeyboard.WillShowNotification 
UIDevice.OrientationDidChangeNotification 

等。这些是NSNotificationCenter预期的合适的NSString

至于摆脱它,因为我有能力这样做,但一种可能的方式是目前还没有我无法验证此第一手是:

声明的addObserver作为一个NSObject,然后用NSNotificationCenter.DefaultCenter.RemoveObserver删除它:

NSObject obj = NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.ProtectedDataWillBecomeUnavailable, handler); 

// do whatever you need to do 
// time to remove: 
NSNotificationCenter.DefaultCenter.RemoveObserver(obj); 
+0

谢谢,这工作(两个!)。 – Krumelur 2011-02-03 10:49:34