Quamber Ali
Quamber Ali

Reputation: 2171

iOS - Creating most Objects as Singleton is the Right choice?

In my current new project i have to get most of the data from internet and that each object of the downloaded data has to be used in many View controllers and should be available all the time. The question is that should i create all the objects as singleton that downloads the data each time the object has not been initialized? or is there any other efficient way of doing this?

Upvotes: 3

Views: 248

Answers (5)

justin
justin

Reputation: 104698

should i create all the objects as singleton that downloads the data each time the object has not been initialized?

No. Create No Singletons ;)

A common problem with a singleton here is that memory you do not reference is not or cannot be easily purged when not referenced.

or is there any other efficient way of doing this?

NSURLCache would seem a good starting point for your usage. You can create multiple caches, if you are dealing with large data sets. They can reduce redundant download requests, and they can store and evict the information on demand.

Sample

URLCache

Intro

http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/

Upvotes: 3

sergio
sergio

Reputation: 69027

Usually, in your case, you would use just one singleton object playing the role of a model in your app (as in model-view-controller). The model, thus, would host all of the objects you download from the internet and could even handle their update, initial download, etc.

Using a single model singleton would allow far more flexibility in case you would ever need a refactoring or redesign.

Upvotes: 1

Valentin Shamardin
Valentin Shamardin

Reputation: 3658

Maybe it's not an answer to question you have posted, but I just want to help you. If you have many objects that you want to get from any controller you can use Core Data. In this case you'll have one data context for whole app.

Upvotes: 0

Engnyl
Engnyl

Reputation: 1380

In your case I would suggest you should not use Singleton in your object classes. Considering the downloaded data might change, updated or deleted at all, I would put a refresh button somewhere and re-fetch the data anytime it is pressed. I would also create the object from the scratch, and avoid using Singleton classes.

Yet if you are sure that the data will not change, save any downloaded data to a plist, core data or etc. and create a Singleton class uses your saved data.

Upvotes: 1

Kamleshwar
Kamleshwar

Reputation: 2997

I think below post may already have answer to your question

On Design Patterns: When to use the Singleton?

Hope this will help you out.

Upvotes: 0

Related Questions