Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

# 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.

As far as I can tell, this was working up until I installed 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?

like image 975
Jason Avatar asked Dec 02 '25 04:12

Jason


1 Answers

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? 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.

like image 146
Driss Zouak Avatar answered Dec 03 '25 19:12

Driss Zouak