迁移到统一 API 和新的引用计数

Migrating to Unified API and new reference counting

我有一个 Xamarin.iOS Classic 项目并将其迁移到 Unified API。

我的代码中有一个视图控制器(简化版):

public class TestViewController : UIViewController
{
    private WeakReference<UIView> _viewRef;

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        _viewRef = new WeakReference<UIView>(View);
        StartTimer();
    }

    private async void StartTimer()
    {
        await Task.Delay(1000);
        // _viewRef is not alive here
    }
}

[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
    UIWindow _window;

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        _window = new UIWindow(UIScreen.MainScreen.Bounds);

        var testController = new TestViewController();
        _window.RootViewController = testController;

        _window.MakeKeyAndVisible();

        return true;
    }
}

这里的奇怪行为是 _viewRef 弱引用变得不活跃。所以看起来视图控制器的 托管视图实例被垃圾收集了 。尽管如此,我可以使用 UIViewController.View 属性 毫无问题地访问 UIView。

经典API项目没有这个问题。我想这里的差异是由 Unified API.

使用 Xamarin 的 new Refcount 引起的

奇怪的是,然后我从空白开始一个Unified API项目,问题也无法重现。

什么会导致这种行为?

这是设计使然,没有理由让本机 UIView 实例的受管对等点保持活动状态(在您的特定测试用例中),因此它已被垃圾收集。

如果我们稍后发现需要托管对等点,则会创建一个新实例。

这个答案对正在发生的事情提供了更深入的解释:Is this a bug in MonoTouch GC?(但是你需要仔细阅读两行之间的内容,因为这回答了相反的问题)。