Skip to content

Instantly share code, notes, and snippets.

@Krumelur
Created April 26, 2015 20:02
Show Gist options
  • Save Krumelur/f59e6d34cd79cd03936a to your computer and use it in GitHub Desktop.
Save Krumelur/f59e6d34cd79cd03936a to your computer and use it in GitHub Desktop.
using System;
using UIKit;
namespace MemoryTest
{
public class CustomView : UIView
{
public int magicNumber;
}
public class CustomButton : UIButton
{
public CustomButton() : base(UIButtonType.System)
{}
public int someValue;
~CustomButton()
{
Console.WriteLine ("Finalized button");
}
}
public partial class ViewController : UIViewController
{
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Test 1: add a subclass of UIView without holding a reference to it.
// How is it possible that the unmanaged subview can be cast back to a managed one
// and I can access the correct value of magicNumber?
this.Add(new CustomView { magicNumber = 42 });
// Test 2: add a subclassed button. This will crash if the button is clicked.
// Why would it retain a UIView but not a UIButton?
var btn = new CustomButton () {
Frame = new CoreGraphics.CGRect(0, 20, 320, 40),
someValue = 4711
};
btn.SetTitle ("Click me", UIControlState.Normal);
btn.TouchUpInside += (sender, e) => {
btn.RemoveFromSuperview();
};
this.Add (btn);
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
GC.Collect ();
GC.WaitForPendingFinalizers ();
GC.Collect ();
var customView = this.View.Subviews [2] as CustomView;
Console.WriteLine ("Magic number: " + customView.magicNumber);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment