【发布时间】:2011-09-15 11:24:11
【问题描述】:
在使用 Monotouch 时,我一直想知道两种情况。他们处理保留对UIViewController 或UIView 的引用的要求。
示例一(我在 MT 错误数据库中找到)。它正在实现MKMapViewDelegate,并且从GetViewForAnnotation 返回的视图将被垃圾回收,除非保留托管引用:
class MapViewDelegate : MKMapViewDelegate
{
public override MKAnnotationView GetViewForAnnotation (MKMapView mapView, NSObject annotation)
{
var myAnnotation = annotation as MyAnnotation;
var view = new MKPinAnnotationView (myAnnotation, "myannotation");
var button = UIButton.FromType (UIButtonType.DetailDisclosure);
view.RightCalloutAccessoryView = button;
// I have had this fail as "invalid selector", and also a SIGSEGV crash
button.TouchDown += delegate {
Console.WriteLine("I was touched!");
};
annotationView = view;
return annotationView;
}
}
示例二:如果我使用PresentModalViewController(),我似乎能够在没有托管引用的情况下生存:
ModalSettingsController oSettingsController = new ModalSettingsController ( );
this.PresentModalViewController(oSettingsController, true);
在这种情况下,我从未遇到过 NULL 引用、SIGSEGV 或类似的东西。 看起来在这种情况下“某事”正在保留参考。
我遇到的问题是:如果我要使用纯 C# 环境而没有 ObjC 世界,那么示例一中的代码将毫无问题地工作;视图已创建并分配给其他东西,这意味着存在引用。但由于第一个示例中返回的视图返回到 ObjC 并且没有托管引用,GC 将清除托管版本。这让我有点困惑。我怎样才能确定在哪些情况下我必须保留参考资料,什么时候不需要? 我是否必须查看 Apple 的文档并查看接收器是否保留视图或控制器?
【问题讨论】:
标签: .net objective-c mono garbage-collection xamarin.ios