【问题标题】:CLLocationManager is always null -Delegate implementation is a Singleton Class (Subclass of NSObject instead of Subclass of UIViewController)CLLocationManager 始终为 null -Delegate 实现是单例类(NSObject 的子类而不是 UIViewController 的子类)
【发布时间】:2012-01-20 14:55:59
【问题描述】:

是否可以将 CLLocationManager 委托方法放在作为 NSObject 的子类而不是 UIViewController 的 Singleton 类中?我想这样做,因为我想从 App Delegate 调用 Singleton 并在 UI 加载时开始获取坐标

我有一个 locationcontroller 类,其中有以下初始化代码

static locationController *sharedLocController = NULL;
+(locationController *) getSharedController
{   
    if (sharedLocController !=nil)
    {
        NSLog(@"locationController has already been created.....");
        return sharedLocController;
    }
    @synchronized(self)
    {
        if (sharedLocController == nil)
        {
            sharedLocController = [[self alloc] init];

        }
    }
    return sharedLocController;
}
//==============================================================================
+(id)alloc
{

    @synchronized([locationController class])
    {

        NSAssert(sharedLocController == nil, @"Attempted to allocate a second instance of a sharedLocMgr singleton.");
        sharedLocController = [super alloc];
        return sharedLocController;
    }
    return nil;
}
//==============================================================================
-(id)init
{
    self = [super init];

    if(sharedLocController !=nil)
    {

        if(!self.locMgr)
        {
            [self initLocationManager];

        }
    }



    return sharedLocController;
}
//==============================================================================
-(void)initLocationManager
{


    self.locMgr = [[CLLocationManager alloc] init];

    self.locMgr.delegate = self;
    self.locMgr.distanceFilter = kCLDistanceFilterNone;
    self.locMgr.desiredAccuracy = kCLLocationAccuracyBest;
    [self.locMgr startUpdatingLocation];
    NSLog(@"location manager object %@", locMgr);
}

问题是 self.locMgr 对象始终为空。 谢谢

【问题讨论】:

    标签: ios core-location cllocationmanager


    【解决方案1】:

    摆脱你的 alloc 函数。这不是必需的,它返回 nil,这意味着这个 init 调用被一个 nil 指针调用:

    sharedLocController = [[self alloc] init];
    

    【讨论】:

      【解决方案2】:

      是的,可以将它们放在NSObject 子类中,这可能是一个单例。我使用类似的东西:

      @interface MyCLController : NSObject <CLLocationManagerDelegate> {
          CLLocationManager *locationManager;
      }
      
      ...
      
      @end
      

      虽然它不是单例。

      【讨论】:

        猜你喜欢
        • 2018-07-13
        • 1970-01-01
        • 1970-01-01
        • 2016-12-26
        • 2015-03-14
        • 2023-03-28
        • 1970-01-01
        • 2017-07-02
        • 1970-01-01
        相关资源
        最近更新 更多