3

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?

Jason
  • 86,222
  • 15
  • 131
  • 146

2 Answers2

2

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.

Driss Zouak
  • 2,381
  • 2
  • 26
  • 39
  • 1
    Aha!! My UIButton and UIBarButtonItem were locally scoped. I made them class level instead, and that seems to have resolved the problem!! Thanks for pointing me in the right direction. – Jason Apr 09 '11 at 20:36
0

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291