简体   繁体   English

应用导航栏按钮事件时应用崩溃

[英]app crashes when handling navbar button event

In my app, I have a navbar button that allows the user to pop back to the top of the navigation stack. 在我的应用程序中,我有一个导航栏按钮,允许用户弹回导航堆栈的顶部。 This has been there for a while and has been working fine. 这已经有一段时间了,一直很好。 However, when I build with MT 4.0 it crashes. 但是,当我使用MT 4.0构建时,它会崩溃。

# in constructor
UIButton btn = UIButton.FromType(UIButtonType.Custom);
btn.Frame = new RectangleF(0,0,29,29);
btn.SetBackgroundImage(UIImage.FromFile("images/Home_button.png"),UIControlState.Normal);
btn.TouchDown += delegate {
  this.NavigationController.PopToRootViewController(true);
};
UIBarButtonItem bar = new UIBarButtonItem(btn);
this.NavigationItem.RightBarButtonItem = bar;           

The button is drawn correctly, but the app crashes when the button is pressed. 按钮绘制正确,但按下按钮时应用程序崩溃。 If I change the delegate to just do a Console.WriteLine() it still crashes. 如果我将委托更改为仅执行Console.WriteLine(),它仍然会崩溃。

As far as I can tell, this was working up until I installed MT 4.0. 据我所知,这是在我安装MT 4.0之前一直在努力。

The exception it shows when it crashes is 崩溃时显示的异常是

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object   at (wrapper managed-to-native) 
MonoTouch.UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)   at 
MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in 
/Users/plasma/Source/iphone/monotouch/UIKit/UIApplication.cs:26 at 
Application.Main (System.String[] args) [0x00000] in 
/Users/jason/Projects/myproj/myproj/AppDelegate.cs:44

Navigating using the back button is working normally. 使用后退按钮导航正常。 Is this a bug, or am I doing something wrong? 这是一个错误,还是我做错了什么?

Quick question, but I ask this because I did this to myself several times, the reference to your View, it isn't locally scoped in your Main's method by chance, is it? 快问题,但是我问这个是因为我多次对自己这样做了,对你的View的引用,它不是偶然在你的Main方法的本地范围内,是吗? What happens is that the reference is lost but the screen still appears but then as soon as you want to do something it's been garbage collected. 会发生什么事情是参考丢失但屏幕仍然出现但是一旦你想做某事它就被垃圾收集了。

The Back button is owned by the navigation controller itself, which would have been referenced likely by your Window, and therefore it can really through you off. 后退按钮由导航控制器本身拥有,您可能已经通过Window引用了它,因此它可以真正通过您关闭。

Just as a quick reminder, I had a similar crash when not the button was created on a local variable but the view containing the button. 就像快速提醒一样,当没有在局部变量上创建按钮但是包含按钮的视图时,我发生了类似的崩溃。 I've described the solution here . 我在这里描述了解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM