I’ve been learning Objective-C and just recently started using classes (instead of having everything in the ViewController). I’m running into a problem in that I don’t know what to do with variables that I want to be accessible in other classes.
I have a NSArray of UIView that is created in my “ViewController”. It is then passed to my “LayoutManager” that sets their frame based on the screen size. This array also needs to be accessed from my “BlockManager” and “ColorManager”.
What is the best way to handle this array and other variables in similar cases. Should I use a global variable, and if so, how? Or is there a better way to do it?
Global variables are generally a bad idea in object-oriented programming (the singleton pattern being possibly an acceptable exception, though opinions vary). In general you also want to avoid sharing raw data and letting anyone at all do whatever they want to it — you end up needing to give everyone internal implementation knowledge of everyone else and it becomes exceedingly difficult to manage.
In your case it sounds like
LayoutManageris a one-shot task (or possibly once per rotation?), so it would be fine to phrase that object interaction as ‘here are my views, please size them’ and to make that the entire lifecycle of the object. So you’d pass the array to init, you’d let the class run once then you’d release it.If
BlockManagerandColorManagerhave something they need to communicate back to your view controller concerning its views, you should probably create suitable delegate protocols. Then the line of communication is that they let the view controller know whatever it is they’ve calculated it should know and it is responsible for taking action on the array.