我在我的项目中遇到了问题,并试图创建一个示例项目来重现它,我能够做到。
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(() => {
}));
}));
});
}
}
}
}