c# – 何时何地调用RemoveObserver
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 何时何地调用RemoveObserver,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2540字,纯文字阅读大概需要4分钟。
内容图文
![c# – 何时何地调用RemoveObserver](/upload/InfoBanner/zyjiaocheng/767/b7911a6c5c7b4a39b5a5a5ed373a2adb.jpg)
我有一个UITextView子类,我添加了一个NSNotificationCenter观察器.但是我又在哪里删除了观察者呢?
我的代码:
_textDidChangeNotification = UITextView.Notifications.ObserveTextDidChange(TextDidChange);
在Objective C中,我会在dealloc方法中执行此操作,但我不确定在C#中的相同位置
据我所知,我应该打电话给我
_textDidChangeNotification.Dispose()
我曾尝试过
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_textDidChangeNotification.Dispose();
}
}
但它永远不会被称为.
完整的课程,按要求:
public class PlaceholderTextView : UITextView
{
public string Placeholder
{
get { return PlaceholderLabel.Text; }
set
{
PlaceholderLabel.Text = value;
PlaceholderLabel.SizeToFit();
}
}
protected UILabel PlaceholderLabel { get; set; }
protected NSObject _textDidChangeNotification;
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
AdjustPlaceholderHidden();
}
}
public PlaceholderTextView()
{
SetupLayout();
_textDidChangeNotification
= UITextView.Notifications.ObserveTextDidChange(TextDidChange);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_textDidChangeNotification.Dispose();
}
protected void SetupLayout()
{
PlaceholderLabel = new UILabel(new CGRect(0, 9, 0, 0));
PlaceholderLabel.TextColor = UIColor.FromWhiteAlpha(0.702f, 1f);
AddSubview(PlaceholderLabel);
}
protected void AdjustPlaceholderHidden()
{
if (Text.Length > 0)
{
PlaceholderLabel.Hidden = true;
}
else
{
PlaceholderLabel.Hidden = false;
}
}
protected void TextDidChange(object sender, Foundation.NSNotificationEventArgs args)
{
AdjustPlaceholderHidden();
}
}
解决方法:
我会在ViewWillDisappear中这样做:
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear (animated);
SubscribeMessages ();
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
UnSubscribeMessages ();
}
public void SubscribeMessages ()
{
_hideObserver = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, OnKeyboardNotification);
_showObserver = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, OnKeyboardNotification);
}
public void UnSubscribeMessages ()
{
if (_hideObserver != null) NSNotificationCenter.DefaultCenter.RemoveObserver (_hideObserver);
if (_showObserver != null) NSNotificationCenter.DefaultCenter.RemoveObserver(_showObserver);
}
或者像Xamarin示例代码here中的ViewDidDis似
更新
我明白你的意思了,我怀疑某些事情阻止了自定义视图被垃圾收集.你有没有看过这个blog post可能会有所帮助.
同样从这个sample code看起来你正在调用dispose但是它们在ViewDidUnload here上清空了自定义视图:
内容总结
以上是互联网集市为您收集整理的c# – 何时何地调用RemoveObserver全部内容,希望文章能够帮你解决c# – 何时何地调用RemoveObserver所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。