I have an app that when the main home screen is loaded I check for sync updates in the background. If there is a slow connection or a user who moves through the app fast a bunch of these requests could stack up in the background. To prevent this I want to implement a BOOL variable that I toggle YES or NO to prevent multiple requests from going out to check for sync.
So my code would be something like this when a request is started:
NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
NSString *key = [NSString stringWithFormat:kVarAllowSyncRequest, aManufacturerID];
[d setBool:NO forKey:key];
I know this will work but this will be called 100’s of times during my app’s use – is that something I even need to worry about?
Is there a better approach to doing this?
User Defaults is a good place to put preferences and information that doesn’t change or need to be accessed more than two or three times per session. Accessing the defaults means hitting the disk, which is slow; you don’t want to use it for something like checking a flag many times a minute.
The application delegate is a handy place to store information that genuinely needs to be accessible to many objects in your application, since it is always accessible via
[[UIApplication sharedApplication] delegate], but you should think carefully about your app design before weighing that object down with lots of ivars just because it seems convenient.Presumably there is only one object, possibly a view controller, which is responsible for sending out these requests. That is the place to put the flag. From your description, it doesn’t sound like you need an app-global variable at all. The flag is only used by the object which initiates the request, and so it is the only object which needs to know about it. The flag can be an ivar.
If, in fact, you have a class, which may have many instances each of which will send out a request, then the correct solution would be to have a class-level flag that any instance has access to. This is straightforward. In your implementation file, declare a variable to hold the flag:
It is declared
staticto make it only visible in this “compilation unit” (loosely, in this file).Then you create a class method each to set and get this flag:
Now, each time one of your
RequestMakerinstances wants to start a request, it should check the flag; if it’sYES, then you can turn the flag off and start a request. You will also need to make sure to reset the flag when the request finishes.(This all assumes that you are not explicitly working on different threads for your requests. If you are, then you should look into GCD queues and maybe semaphores. There’s an excellent set of writeups by Mike Ash that make fun reading even if you don’t want to use GCD.)