【问题标题】:memory management issues in xamarin.iosxamarin.ios 中的内存管理问题
【发布时间】:2017-08-02 09:30:18
【问题描述】:
就我在 xamarin 中的工作而言,在视图控制器中声明全局变量非常重要,否则当涉及到绑定和所有相关问题时,它可能会被垃圾回收。
同样,对于 nsnotification,我们必须拥有 nsobject 类型的全局引用,并在不需要 nsnotification 时删除 nsobject。
没有可用的实用文档,这让原生 iOS 开发人员对 xamarin.ios 感到沮丧
对于任何成为 xamarin.ios 开发者的 ios 开发者来说,建议一些这样的事情将是一个很好的帮助
【问题讨论】:
标签:
ios
memory-management
xamarin.ios
garbage-collection
automatic-ref-counting
【解决方案1】:
在每个 ViewController 中编写以下代码:
public override void ViewDidDisappear (bool animated)
{
//Executed when we navigate to other view, moving this ViewController in Navigation stack
//1. UnSubscribe All Events Here (Note: These must be SubScribed back in ViewWillAppear)
btnLogin.TouchupInside -= OnLoginClicked
//2. Remove Any TapGuestures (Note: These must be added back in ViewWillAppear)
if (singleTapGuesture != null)
{
scrollView.RemoveGestureRecognizer(singleTapGuesture);
singleTapGuesture.Dispose();
singleTapGuesture = null;
}
//3. Remove any NSNotifications (Note: These must be added back in ViewWillAppear)
//4. Clear anything here, which again initializes in ViewWillAppear
if (ParentViewController == null) {
//This section will be executed when ViewController is Removed From Stack
//1. Clear everything here
//2. Clear all Lists or other such objects
//3. Call Following Method which will clear all UI Components
ReleaseDesignerOutlets ();
}
base.ViewDidDisappear (animated);
}
这将在 ViewController 被导航或从堆栈中删除时清除所有不需要的对象。
对于 UITableViews,使用 WeakDataSource 和 WeakDelegate。
还有更多基于以下链接:
Ref 1
Ref 2