Bug 17533 - Crash when setting a UITextFieldDelegate method in an UIAlertView
Summary: Crash when setting a UITextFieldDelegate method in an UIAlertView
Alias: None
Product: iOS
Classification: Xamarin
Component: Xamarin.iOS.dll ()
Version: master
Hardware: PC Mac OS
: --- normal
Target Milestone: Untriaged
Assignee: Bugzilla
Depends on:
Reported: 2014-01-31 06:22 UTC by Alek Slater
Modified: 2014-01-31 09:53 UTC (History)
2 users (show)

Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.

Please create a new report on Developer Community or GitHub with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:

Description Alek Slater 2014-01-31 06:22:21 UTC
It crashes for me when I try to set a UITextFieldDelegate method in an UIAlertView.

private void ShowAlert()
	UIAlertView al = new UIAlertView ("Test", "Test", null, "Cancel", null);
	al.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
	al.GetTextField (0).ShouldChangeCharacters += ShouldChangeCharacters;
	al.Show ();

private bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
	if (replacementString != null && replacementString.Length >= 20)
		return false;
	return true;
Comment 1 Sebastien Pouliot 2014-01-31 09:31:38 UTC
That's because `al` is a local variable. When the method `ShowAlert` returns there is no *managed* reference to it - so the GC is allowed to collect it.

However the *native* UIAlertView still exists and when it tries to callback to managed cod (to run the delegate code) it will point to released memory (and crash).

You need to ensure your managed object lifecycle match the native one, i.e. if you want the UIAlertView to exists after the call to `ShowAlert` then promote the local variable to a field. Thay way it won't be GC'ed (unless you dispose the field or when the field's owner type is disposed).
Comment 2 Alek Slater 2014-01-31 09:53:02 UTC
Thx, really makes it quite tedious to use this without a tonne of boiler plate, but if thats the only way, no problem..