How to handle events from storyboard elements – subscriptions or actions

I'm fairly new to Xamarin so I apologize if this is a trivial question. I’m using Xamarin with Visual Studio and a Mac connected via LAN, just to clear that up.

If you double click a button in a storyboard, an action for the TouchUpInside event will be created for you with a partial method definition in ViewController.designer.cs, and a partial method definition in ViewController.cs.

partial void MyButton_TouchUpInside(UIKit.UIButton sender);

partial void MyButton_TouchUpInside(UIKit.UIButton sender)
{
    //Do stuff
}

Instead of double clicking, this can also be achieved in the Events tab in the Properties pane with the button selected in the storyboard. Here you can type the name of the action you which to create for any given event and hit enter. This will create the partial methods as mentioned above.

image

This is sort of the Xamarin equivalent of how it’s done in Xcode, with an event of a given view beeing connected to an IBAction in the ViewController.
This approach however, is not taken in many of the tutorials and sample apps, e.g. the Phoneword app. Here you create a subscription using a lambda expression:

MyButton.TouchUpInside += (object sender, EventArgs e) => {
    //Do stuff
}

According to the Handle Clicks recipe, in case you subscribe to a delegate method instead of using a lambda or an anonymous delegate, you must unsubscribe (-=). This begs the question; are subscriptions using lambda expressions leaky by nature, as you cannot unsubscribe? In Windows applications, using lambdas to subscribe to events is certainly a source of memory leaks.

All of the above raises the following questions:

  • Do these two approaches compile to the same thing or are there differences you need to know about?
  • Is the compiled version of one or both approaches equivalent to IBActions in Xcode?
  • Will the use of subscriptions lead to memory leaks if not implemented carefully
  • Are actions garbage collected automatically without the need to unsubscribe?
  • And probably the most important question of all; should you strive to use one approach over the other

Posts

Sign In or Register to comment.