【问题标题】:How to avoid multiple allocating of CLLocationManager instance?如何避免多次分配 CLLocationManager 实例?
【发布时间】:2012-06-23 10:23:27
【问题描述】:

我在我的应用程序中使用核心位置框架,并在 didUpdateToLocation 方法中向服务器发送更新的位置,我分配 CLLocationManager 实例的视图是登录后的第二个视图,从登录视图调用此视图并在 dealloc 中释放 CLLocationManager方法,但每次我来自登录屏幕时,然后 didUpdateToLocation 方法调用两次和三次,具体取决于我来自登录视图的次数,所以问题是什么,我该如何避免这种情况?

【问题讨论】:

    标签: iphone ios5 gps xcode4.2 core-location


    【解决方案1】:

    如果您想避免多次分配 CLLocationManager 实例,请将实例定义为 appDelegate 的属性

    每次您需要获取此实例时,您都会这样做

    YouAppDelegate *appDelegate = (YouAppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.yourLocationInstance;
    

    【讨论】:

      【解决方案2】:

      我通常只使用singleton 来处理这类事情。只需定义一个类方法(在方法定义上使用 + vs a -)。下面是一个单例定义的例子:

      +(id)sharedLocationManager
      {
      static BCLocationManager *sharedLocationManager;
      @synchronized(self)
      {
          if (!sharedLocationManager)
          {
              sharedLocationManager = [[BCLocationManager alloc] init];
          }
      
          return sharedLocationManager;
      }
      return sharedLocationManager;
      }
      

      基本上,您定义了一个类的静态实例,并且仅在它不存在时才对其进行初始化。使用单例,您永远不会访问实例 init 函数。始终将单例访问器的结果分配给适当的指针,如下所示:

      BCLocationManager * testInstance = [BCLocationManager sharedLocationManager]; 
      

      现在您所要做的就是包含适当的 header.h,您的应用程序中的每个人都可以看到您的位置管理器的单个实例。只要您不使用 init 实例,您就永远不会创建多个实例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-18
        • 2016-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-20
        • 1970-01-01
        相关资源
        最近更新 更多