迁移到统一 API 和新的引用计数 [英] Migrating to Unified API and new reference counting

查看:31
本文介绍了迁移到统一 API 和新的引用计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I had a Xamarin.iOS Classic project and migrated it to Unified API.

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

I have a view controller in my code (simplified version):

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.

The strange behaviour here is that _viewRef weak reference becomes not alive. So it seems like view controller's managed view instance is garbage collected. Nonetheless I can access UIView using UIViewController.View property without any problems.

经典 API 项目没有这个问题.我想这里的差异是由统一 API 使用 Xamarin 的 new Refcount 引起的.

Classic API project didn't have this problem. I suppose the difference here is caused by using Xamarin's new Refcount by Unified API.

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

What is really strange is that then I start a Unified API project from blank the problem also cannot be reproduced.

什么会导致这种行为?

推荐答案

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

This is by design, there is no reason to keep the managed peer for the native UIView instance alive (in your particular test case), so it's garbage collected.

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

If we find that we need a managed peer at a later point, a new instance is created.

这个答案对正在发生的事情提供了更深入的解释:这是 MonoTouch GC 中的错误吗?(但是您需要在两行之间阅读一些内容,因为这回答了相反的问题).

This answer provides a more in-depth explanation of what's happening: Is this a bug in MonoTouch GC? (however you need to read a bit between the lines, because this answers the reverse question).

这篇关于迁移到统一 API 和新的引用计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆