views:

67

answers:

3

Hi

I have two views with their own .h and .m files of course. How can I declare a bool (or any variable for that matter) in one view and be bale to access it in another view?

Thanks.

A: 

You can just take a reference to the view containing the bool and get the variable using a getter.

If you want app wide variables, you could put them in the AppDelegate, but I highly recommend against that since it tightly couples classes.

Rengers
A: 

Objective C is a superset of plain ANSI C, so you would create and use global variables exactly the same way as in old-fashioned C.

In exactly one .m or .c file, put:

BOOL gMyGlobalBoolVar = NO;  // or YES, depending on whatever initial state is needed

I might place these in a centralized singleton class, such as your appdelegate .m file, or in a separate .c file, such as myGlobals.c. I usually place these after the #imports/includes but before any class instantiations to clarify that they can be accessed outside of any class.

In the .h files for all classes where you want to access gMyGlobalBoolVar, put:

extern BOOL gMyGlobalBoolVar;

Then just use them anywhere in the class:

if ( [ self dogHasFleas ] ) { 
  gMyGlobalBoolVar = YES; 
}

The use of global variables is currently not "politically correct", but for quick code that you will never try to publish, reuse, extend, or hunt for gnarly bugs, they work just fine like they did in almost every computer and programming language from 50 or so years ago.

hotpaw2
Im confused as to why they are so fought against. I do plan on publishing this app and so preferably have it neat, tidy, swift and nippy.So whats a good alternative if I really need to access this variable globally?
Josh Kahane
A: 

Create a data model class. Instantiate it in your app delegate, and pass it along to your view controllers. Use Key-Value Observing to track changes to the model in your view controllers. See my answer here: http://stackoverflow.com/questions/2224285/how-do-i-display-and-calculate-numbers-from-a-database-on-iphone/2231980#2231980

"Why shouldn't I use globals? It can't hurt just this once." This is a bad habit to get into. Avoiding global variables makes your code easier to read and reuse, easier to extend, and easier to debug.

Shaggy Frog