4

我在我的项目中遇到了问题,并试图创建一个示例项目来重现它,我能够做到。

https://bitbucket.org/theonlylawislove/xamarinnavigationcontrollermemoryleak

问题是,当我展示 UINavigationController 时,导航控制器或其根视图控制器永远不会被垃圾收集。它确实在 iOS 模拟器中工作。为什么这种内存泄漏只发生在设备上?如果您在设备上运行示例项目,您将永远不会在调用的解构器中看到 Console.WriteLine。

我正在使用 XCode5 和 Xamarin.iOS 7.0.4.171(商业版)

这是我用来演示泄漏的 AppDelegate。

[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
    UIWindow window;
    public override bool FinishedLaunching (UIApplication app, NSDictionary options)
    {
        window = new UIWindow (UIScreen.MainScreen.Bounds);
        window.RootViewController = new UINavigationController(new RootController ());
        window.MakeKeyAndVisible ();

        return true;
    }

    class RootController : UIViewController
    {
        public RootController ()
        {
            NavigationItem.RightBarButtonItem = new UIBarButtonItem("Present", UIBarButtonItemStyle.Bordered, (o,e) => {
                PresentViewController(new NavigationController(), true, new NSAction(() => {}));
            });
        }
    }

    class NavigationController : UINavigationController
    {
        public NavigationController ()
            :base(new TestController())
        {

        }

        ~NavigationController()
        {
            Console.WriteLine("~NavigationController");
        }

        class TestController : UIViewController
        {
            ~TestController()
            {
                Console.WriteLine("~TestController");
            }

            public override void ViewDidAppear (bool animated)
            {
                base.ViewDidAppear (animated);
                Task.Factory.StartNew (() => {
                    Thread.Sleep(2000);
                    NSThread.MainThread.InvokeOnMainThread(new NSAction(() => {
                        DismissViewController(true, new NSAction(() => {

                        }));
                    }));
                });
            }
        }
    }

}
4

1 回答 1

3

这只是保守收集器的副作用,堆栈上可能有一些垃圾,但使用您的应用程序将消除垃圾并允许释放对象。

如果您使用使用精确系统的 SGen,您将看到对象立即消失。

于 2013-11-11T17:21:24.457 回答