Custom layer with UIView memory leak

iphooiphoo BYMember ✭✭

I use following sample from Xamarin docs to provide custom layer for my UIView:

public class BlueView : UIView
        {
            [Export("layerClass")]
            public static Class GetLayerClass()
            {
                return new Class(typeof(BlueLayer));
            }

            public override void Draw(CGRect rect)
            {
                // Do nothing, the Layer will do all the drawing
            }

            protected override void Dispose(bool disposing)
            {
                Console.WriteLine("BlueView disposed");
                base.Dispose(disposing);
            }

            public class BlueLayer : CALayer
            {
                public BlueLayer()
                {
                    // if you uncomment this line this layer instance will never get disposed;
                    // there is no such problem if you add sublayer outside BlueLayer constructor;

                    ////AddSublayer(new CALayer());
                }

                public override void DrawInContext(CGContext ctx)
                {
                    ctx.SetFillColor(0, 0, 1, 1);
                    ctx.FillRect(Bounds);
                }

                protected override void Dispose(bool disposing)
                {
                    Console.WriteLine("BlueLayer disposed");
                    base.Dispose(disposing);
                }
            }
        }

Whenever BlueView instance is not used any more it gets GC-ed with backing BlueLayer instance as well.
But if I uncomment this line in BlueLayer constructor AddSublayer(new CALayer()); Dispose() of BlueLayer never called.

If I add sublayer outside BlueLayer constructor everything works as expected.

Question here: Is it Xamarin bug?
I cannot find any information that it is not allowed to add sublayers in native init() in Apple docs.

Tagged:
Sign In or Register to comment.