VeryPoliteNerd
VeryPoliteNerd

Reputation: 253

GeoFenceController with CLLocationManager as singleton?

I have a GeoFence class. I'm debating myself whether or not it should be a singleton. My code works either way and I have read a couple of articles and posts here on SO about it. But I didn't find any good rules for when it is correct to use a singleton.

I can't really come up with any reason it shouldn't be though, and I have a few reasons it should; the classic "there shall be only one!" and also that the class doesn't really have any dependencies, as far as I can tell, other than the locationManager object which it might as well create itself since it isn't needed elsewhere, and I don't believe any special implementations could ever be required. I don't see any point in injecting the locationManager for this reason. It does also need to use another shared instance in the app that calls a server to fetch some data. The most important reason to make it a singleton I think would be that it keeps track of monitored regions and it stores some data related to that and some timestamps and other minor stuff in NSUserDefaults. Another instance of the class I fear could cause inconsistent behaviour of the app.

My code is meant to be added to an existing app as an extension.

I don't think posting my code is really relevant, but I'll explain briefly what the class does: On instantiation it will begin monitoring the users location and continue to do so in the background too. It will request a list of locations from a server and receive those based on the current location of the device. These locations will be sorted and stored and the 20 locations closest to the device will be monitored for entry. That's pretty much the basics of it. Geofencing.

I would love some arguments for and/or against the use of a singleton in this case.

Upvotes: 0

Views: 163

Answers (1)

Alex Pavlov
Alex Pavlov

Reputation: 1001

GeoFenceController will use a global resource - the pool of 20 regions available to your app. That pool is implemented in such a way, that not only a capacity is shared among all the instances of CLLocationManager, all the regions will be effectively shared as well, as all instances of CLLocationManager will report enter/exit events to their delegates for all regions. Tracking capacity limits and "own" events will result in a convoluted code.

That's why singleton pattern is pretty acceptable here.

Upvotes: 1

Related Questions