2
\$\begingroup\$

I inherited a Xamarin project and I'm trying to find my way. The first task I completed involved creating a new reusable view and adding it to an existing screen. This was iOS specific, so I went and created a new .xib file to add in the relevant storyboard. I had some trouble figuring out how to attach the outlets correctly and I didn't see my view so I added it programmatically, but in the end I got it working. However I ended up using the following code that concerns me a bit:

    // TableviewSearchbarHeader.designer.cs
    [Register ("TableviewSearchbarHeader")]
    partial class TableviewSearchbarHeader
    {
        [Outlet]
        UIKit.UIButton ClearSelectionButton { get; set; }
    }

    // TableviewSearchbarHeader.cs
    public void SetOnClearSelectionButtonPressed(EventHandler OnClearSelectionButtonPressed)
    {
        ClearSelectionButton.TouchUpInside += OnClearSelectionButtonPressed;
    }

    // MyViewController.cs
    public override void ViewDidLoad()
    {
        TableviewSearchbarHeader.SetOnClearSelectionButtonPressed(OnClearSelectionButtonPressed);
    }
    private void OnClearSelectionButtonPressed(object sender, EventArgs e)
    {
        Presenter.ResetFilter(this);
    }

The outlet is not accessible from the VC. So I had to create an entry point for the VC to assign its delegate implementation. But how can I be sure this will not cause a memory leak? This just seems like a code smell, but I couldn't figure out a better way and the docs aren't helpful.

What can I improve?

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to Code Review. Can you tell us more about the purpose of the code? It's an entry point between what and the delegate? \$\endgroup\$ – Mast Jul 11 '20 at 15:36
  • \$\begingroup\$ @Mast The purpose is to have the OnClearSelectionButtonPressed method in the ViewController called when the user presses the button. This works by using the += operator on the button's TouchUpInSide property and passing the method's name. However, in the ViewController where I have the method I want to assign, I don't have access to the button. So I created SetOnClearSelectionButtonPressed in TableviewSearchbarHeader.cs where I do have access to the button, and I call this method from my ViewController. So now I don't have to expose the button, and OnClearSelectionButtonPressed gets called. \$\endgroup\$ – Kevin Jul 11 '20 at 15:49
  • 1
    \$\begingroup\$ @Mast My concern is that by doing it like this maybe I'm creating a memory leak somewhere. I'm unsure whether the button holds a reference to the ViewController's method and if that reference ever releases. \$\endgroup\$ – Kevin Jul 11 '20 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.