gpt4 book ai didi

xamarin.ios - 为什么MonoTouch GC无法杀死refcount> 1的托管对象?

转载 作者:行者123 更新时间:2023-12-04 04:12:40 26 4
gpt4 key购买 nike

我想我已经接近了解how Mono GC and ObjC ref counting live together了。

The way it works is that when a native object has a reference count of 1, we do not prevent the managed instance from getting garbage collected. As soon as the reference count increases above 1, we prevent the managed instance from getting garbage collected.

This is because a managed object may contain user state. For managed objects which are mirroring a corresponding native object (such as the managed UIView instance) MonoTouch knows that the instance can not contain any state, so as soon as no managed code has a reference to the managed instance, the GC can collect it. If a managed instance is required at a later stage, we just create a new one.


因此,如果我创建一个继承 CustomButtonUIButton,将其作为 subview 添加到我的 View中,让托管引用超出范围,然后运行GC,则此 托管 CustomButton仍然不符合收集条件。
为什么不能收集?当然,它可能具有诸如属性 之类的托管状态,但是如果没有托管对象与它的链接,谁在乎这种状态呢?它也可能消失了,为什么不能呢?
我在考虑一个可能的原因:订阅 CustomButton事件不会使GC保持事件状态,因此当对象被收集时,事件将停止触发。这可能会导致意外的行为。
这样对吗?即使没有人链接受管理对象,还有其他原因可以使该受管理对象保持事件状态吗?

最佳答案

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 代码可能引用了该对象,这可能导致该对象稍后再次出现在托管代码中。

我相信代码示例将说明将发生的情况:

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无法收集可能具有状态的托管对象的原因。这个特定示例实际上不会忘记重要的 secret ,因为Subviews数组会自动缓存在托管代码中-但这通常不是正确的。

关于xamarin.ios - 为什么MonoTouch GC无法杀死refcount> 1的托管对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13064669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com