Ketan Shinde Ketan Shinde -4 years ago 78
Objective-C Question

How to get shared instance of location manger in synchronize

Hy, I want to get the background location updates, so I wrote the below code and make it synchronized to keep it safe from multithreading. So I have two questions:


  • Do I really need to synchronize the piece of code, all I am doing in App is just running background task? I never created any special
    NSThread
    type to support multithreading and don't require as such?

  • Whenever I need to start the location updates, I call like this:

    CLLocationManager *locationManager = [LocationTracker sharedLocationManager];
    locationManager.delegate = self;
    [locationManager startUpdatingLocation];


    Is correct way to call?

    + (CLLocationManager *)sharedLocationManager {
    static CLLocationManager *_locationManager;
    @synchronized(self) {
    if (_locationManager == nil) {

    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    [_locationManager requestAlwaysAuthorization];
    _locationManager.distanceFilter = 10;

    if(IS_OS_9_OR_LATER){
    _locationManager.allowsBackgroundLocationUpdates = YES;
    }
    }
    }
    return _locationManager;
    }


Answer Source

Shared instance should be synchronised. You can use @Synchronized or dispatch_once. It is good practice to synchronised the shared instances even you are not using the multiple threads.

+ (instancetype)sharedLocationManager {

      static LocationTracker *sharedInstance_ = NULL;
      static dispatch_once_t onceToken;

      dispatch_once(&onceToken, ^{
        sharedInstance_ = [[LocationTracker alloc] init];
        [sharedInstance_ initialize];
     });

    return sharedInstance_;
}

- (void)initialize {
          _locationManager = [[CLLocationManager alloc] init];
          _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
         [_locationManager requestAlwaysAuthorization];
          _locationManager.distanceFilter = 10;

         if(IS_OS_9_OR_LATER){
            _locationManager.allowsBackgroundLocationUpdates = YES;
         }
}

You can implement the location manager delegates inside the LocationTracker class. Use NSNotificationObserver to update all the classes, which are all expecting location update.

Else follow the below line.

CLLocationManager *locationManager = [LocationTracker sharedLocationManager].locationManager;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download