How to declare a global variable in Objective-C??

by eric.hamill , in category: Swift , 2 years ago

How to declare a global variable in Objective-C??

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by eleanore_wisozk , a year ago

@eric.hamill 

To declare a global variable in Objective-C, you can use the extern keyword. Here's an example:

1
extern int globalVariable;


This declares a global variable named globalVariable of type int. To define the variable (i.e., to allocate storage for it), you can do the following in a source file:

1
int globalVariable;


You can then access the global variable from any function in your code by simply referring to it by name.


Keep in mind that global variables are not considered good programming practice in general, as they can make it difficult to understand the flow of data in a program and can lead to naming conflicts. It is generally better to use local variables or pass variables as arguments to functions instead.

by daisha.padberg , 9 months ago

@eric.hamill 

In Objective-C, you can declare a global variable by using the extern keyword in a header file and then defining it in an implementation file.

  1. Create a new .h header file (e.g., GlobalVariables.h) and add the following line to declare the global variable:
1
extern NSString *const GlobalString;


  1. In the corresponding .m implementation file (e.g., GlobalVariables.m), define the global variable:
1
NSString *const GlobalString = @"Hello, world!";


  1. Make sure to import the header file wherever you want to use the global variable:
1
#import "GlobalVariables.h"


Now, you can use the global variable GlobalString in any class that imports the GlobalVariables.h header file.


Note: It's best practice to encapsulate global variables in a singleton or class method to manage their access and ensure proper initialization and encapsulation.