Question

One of the view controllers in my app allows for downloading files from a server. But a user could navigate to this view controller, hit the "Download" button, and then go back to a previous view controller. If they again navigate to the view controller that has the Download button, they should see progress, or even see that the download has completed.

So it seems to me that the view controller itself cannot hold any reference to the Download operation, which I'm thinking would be a subclass of NSOperation that would handle NSURLConnection stuff, nor could it be the owner of the NSOperationQueue to which the operations get added to.

Doesn't this situation require a singleton download manager? I often see singletons discouraged, but how else would I go about this? Again, downloads can be initiated in view controllers that could be deallocated at any time. Once a download is started though it should finish regardless of whether the user left the screen or not. I want to download everything straight to disk (not in memory). Then, when a user comes to said view controller, I check the download manager to see if the relevant downloads are finished, in progress, or had never started downloading.

Was it helpful?

Solution 2

I think this is one of the few cases were a singleton pattern can be used. It exactly fits the singleton description (via Wikipedia):

In software engineering, the singleton pattern is a design pattern that restricts the Instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

I do it this way in my apps and I've seen it done by others, e.g.:

This post might be also of interest to you. Every iOS app comes with one singleton (AppDelegate) so your class could be just a single instance, that's referenced by the AppDelegate.

OTHER TIPS

I'd use a singleton. Just take care when / where you use singletons. Be sparing and think about the situation before you use one.

Take care with your callbacks for download progress / completion because the singleton will outlive the view controllers making requests. The view controllers need to manage their 'observations' appropriately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top