2

如何在单点触控应用程序中存储/访问全局变量?我在 AppDelegate 的 FinishedLaunching 方法期间检索 GPS 位置(使用 Monotouch.CoreLocation.CLLocationManager)。然后,我如何从该 appdelegate 上的属性访问该信息(例如,从视图)?还是有另一种全局数据的首选方法?

更新:我只想在启动时获取一次位置,然后从我的所有视图中访问该位置。这是我的 AppDelegate - 我想从视图中访问 locationManager 字段。我当然可以添加一个属性来这样做,但我想我的问题是“我如何从视图访问该属性(或者我什至可以,考虑到它是一个委托)”?

// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
    private CLLocationManager locationManager = new CLLocationManager();

    // This method is invoked when the application has loaded its UI and its ready to run
    public override bool FinishedLaunching (UIApplication app, NSDictionary options)
    {   
        locationManager.Delegate = new GpsLocationManagerDelegate();
        locationManager.StartUpdatingLocation();

        window.AddSubview (navController.View);
        window.MakeKeyAndVisible ();        
        return true;
    }

    // This method is required in iPhoneOS 3.0
    public override void OnActivated (UIApplication application)
    {
    }
}
4

2 回答 2

3

通常,大多数人会告诉您避免使用全局变量,而是将您需要的内容传递给委托。(我同意这种观点)。

但是,您可以使用单例类、服务定位器或具有静态字段/属性的静态类在 C#(或任何其他 Dotnet/Mono 兼容语言)中获得类似全局变量的行为。

在您的情况下,我假设您自己编写了 GpsLocationManagerDelegate 类。如果是这样,您可以更改构造函数以获取必要信息的参数(视图、对应用程序委托的引用和/或对位置管理器的引用)并将其存储在您的 GpsLocationManagerDelegate 实例中。如果您没有自己编写 GpsLocationManagerDelegate 并且它没有声明为密封,则将其子类化并创建一个适当的构造函数。

这个例子似乎接近你所追求的:http: //www.conceptdevelopment.net/iPhone/MapKit01/Main.cs.htm

于 2010-01-13T19:23:04.240 回答
1

您应该将 locationManager 设为公共属性,然后您可以从应用程序中的大多数位置访问它,如下所示:

CLLocationManager LocationManager {get;set;}

AppDelegate delegateReference = 
     (AppDelegate)UIApplication.SharedApplication.Delegate;

然后通过以下方式在代码中的任何位置访问 locationmanager:

delegateReference.LocationManager

通常,您应该在 AppDelegate 中设置单例等设置。

于 2011-09-28T00:20:48.343 回答