且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 MonoTouch GC 不能杀死引用计数 > 的托管对象?1?

更新时间:2022-11-01 16:57:28

为什么收不到?当然,它可能有像属性一样的托管状态,但是如果没有从托管对象到它的链接,谁会关心这个状态呢?也可以直接消失,为什么不能?

Why can't it be collected? Of course it may have managed state like properties, but if there is no link to it from managed objects, who cares about this state? It may as well just disappear, why can't it?

本机代码可能会引用该对象,这可能会导致该对象稍后再次重新出现在托管代码中.

Native code might have references to the object, which may cause the object to resurface to managed code again later.

我相信代码示例可以说明会发生什么:

I believe a code sample would illustrate what would happen:

class MyView : UIView {
    public string ImportantSecret;
}

class AppDelegate : UIApplicationDelegate {
    UIViewController vc;
    public override bool FinishedLaunching (UIApplication app, 
                                            NSDictionary options)
    {
        var myView = new MyView ();
        myView.ImportantSecret = "MonoTouchRocks";

        vc = new UIViewController ();
        vc.View = new UIView ();
        vc.View.AddSubView (myView);

        // When this method returns the only place where myView is referenced
        // is from inside the *native* Subviews collection.

        BeginInvokeOnMainThread (() =>
        {
            Console.WriteLine (((MyView) vc.Subviews [0]).ImportantSecret);
            // If the MyView instance was garbage collected and recreated
            // automatically at this point, ImportantSecret would be null.
        });
    }
}

重要:这段代码只是为了说明GC无法收集可能有状态的托管对象的原因.这个特定的示例实际上不会忘记重要的秘密,因为 Subviews 数组会自动缓存在托管代码中 - 但通常情况并非如此.

Important: this code is just to illustrate the reason why the GC can't collect managed objects which may have state. This particular sample would actually not forget the important secret, since the Subviews array is automatically cached in managed code - but this is not generally true.