【问题标题】:Where to implement CLLocationManager在哪里实施 CLLocationManager
【发布时间】:2010-12-24 03:42:38
【问题描述】:

我有一个带有标签栏和 3 个标签的应用。将需要在三个选项卡中的任何一个上知道用户的当前位置。在这种情况下,实现CLLocationManager 的最佳位置是在应用程序委托中吗?

将 CLLocationManager 委托方法放在应用程序委托 m 文件中是否可以(好的做法?)?

您建议我将CLLocationManager 放在哪里,因为我将在三个选项卡中的任何一个中调用-startUpdatingLocation

谢谢

【问题讨论】:

    标签: core-location


    【解决方案1】:

    应用程序委托是放置它的合理位置。另一种选择是创建一个自定义单例工厂类,该工厂类具有一个类方法,该类方法返回您的位置管理器委托并在那里实现委托方法。这将使您的应用委托类更清洁。

    这是一个基于 Peter Hosey 的 "Singletons in Cocoa: Doing them wrong" 的骨架单例类实现。这可能有点矫枉过正,但这是一个开始。在最后添加您的委托方法。

    static MyCLLocationManagerDelegate *sharedInstance = nil; 
    
    + (void)initialize {
        if (sharedInstance == nil)
            sharedInstance = [[self alloc] init];
    }
    
    + (id)sharedMyCLLocationManagerDelegate {
        //Already set by +initialize.
        return sharedInstance;
    }
    
    + (id)allocWithZone:(NSZone*)zone {
        //Usually already set by +initialize.
        @synchronized(self) {
            if (sharedInstance) {
                //The caller expects to receive a new object, so implicitly retain it
                //to balance out the eventual release message.
                return [sharedInstance retain];
            } else {
                //When not already set, +initialize is our caller.
                //It's creating the shared instance, let this go through.
                return [super allocWithZone:zone];
            }
        }
    }
    
    - (id)init {
        //If sharedInstance is nil, +initialize is our caller, so initialze the instance.
        //If it is not nil, simply return the instance without re-initializing it.
        if (sharedInstance == nil) {
            if ((self = [super init])) {
                //Initialize the instance here.
            }
        }
        return self;
    }
    
    - (id)copyWithZone:(NSZone*)zone {
        return self;
    }
    - (id)retain {
        return self;
    }
    - (unsigned)retainCount {
        return UINT_MAX; // denotes an object that cannot be released
    }
    - (void)release {
        // do nothing 
    }
    - (id)autorelease {
        return self;
    }
    #pragma mark -
    #pragma mark CLLLocationManagerDelegateMethods go here...
    

    【讨论】:

    • 我将如何实现单例工厂类?这听起来像是一条干净的路,但我不能 100% 确定从哪里开始。
    • 是的,但您可能还想声明您正在实现CLLocationManagerDelegate 协议。类似@interface MyCLLocationManagerDelegate: NSObject<CLLocationManagerDelegate> { } + (id) sharedMyCLLocationManagerDelegate; @end
    【解决方案2】:

    我只是将我的 LocationManager 直接包含在我的 AppDelegate 中,因为它添加的代码很少。

    但是,如果您要将 LocationManager 包含在 AppDelegate 中,那么您应该考虑使用 NSNotifications 来提醒您的视图控制器您的 AppDelegate 接收到的位置更新。

    查看此链接 Send and receive messages through NSNotificationCenter in Objective-C?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-09
      • 2015-12-18
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多