Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective-c - global variables

How do I declare a variable in the main.m file so that it is available in all the classes?

If I simply declare it in the main function, the compiler says it's undeclared in the class method.

Must I declare it in an object like this?

@public
type variable;
like image 347
thepepp Avatar asked Jan 10 '12 18:01

thepepp


People also ask

How do I declare a global variable in Objective-C?

Somewhere in your header, you would declare a global variable like this: extern int GlobalInt; The extern part tells the compiler that this is just a declaration that an object of type int identified by GlobalInt exists.

What is static in Objective-C?

In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program. This is in contrast to automatic variables, whose lifetime exists during a single function call; and dynamically-allocated variables like objects, which can be released from memory when no longer used.


1 Answers

All you need is to use plain old C global variables.

First, define a variable in your main.m, before your main function:

#import <...>

// Your global variable definition.
type variable;

int main() {
    ...

Second, you need to let other source files know about it. You need to declare it in some .h file and import that file in all .m files you need your variable in:

// .h file

// Declaration of your variable.    
extern type variable;

Note that you cannot assign a value to variable in declaration block, otherwise it becomes a definition of that variable, and you end with linker error complaining on multiple definitions of the same name.

To make things clear: each variable can be declared multiple times (Declaration says that this variable exists somewhere), but defined only once (definition actually creates memory for that variable).

But beware, global variables are a bad coding practice, because their value may be unexpectedly changed in any of files, so you may encounter hard to debug errors. You can avoid global variables using Singleton pattern, for example.

like image 137
iHunter Avatar answered Sep 20 '22 19:09

iHunter