Reputation: 33
I am writing an app that requires access to a set of information from all classes and methods. My query is, what's the most efficient way of doing this, so as to minimise memory usage?
I have taught myself coding and have, of course, come across numerous different methods to solve this whilst trawling the internet. For example:
I could create a global variable such as var info = ...
, which I'd place above a class definition, thus giving access from anywhere in the app.
Or I could create a singleton, GameData
and have the data stored there, e.g. GameData.shared.info
, similarly available from anywhere in the app.
Or I could load the information in the first ViewController
and then pass it around as a parameter.
There are no doubt more methods that I haven't come across, but I wonder which is the most memory-efficient method, if indeed there is such a thing. In my case, I won't need access to a huge amount of data - no more than say sixty or seventy records each with half a dozen fields of text or numbers.
Many thanks
Upvotes: 0
Views: 136
Reputation: 19912
Using dependency injection, that is, passing it as a parameter to any object that requires it, would be the more memory conscious method, since the variable will stop existing "automatically" if you were to replace the whole hierarchy (as long as it's done correctly).
By using a singleton or a global variable, you would have to clear the value yourself.
If the value is not going to disappear during the lifetime of the application, then memory usage doesn't matter, but I would still advice against global variables and suggest using dependency injection.
Upvotes: 1