user218404
user218404

Reputation:

How to declare and change global variable in Objective c

can anyone tell how to declare and change global variables in objective c

Upvotes: 0

Views: 2549

Answers (4)

Global Variable for Complete iPhone Project

For Declare/Define/Use a global variable follow these easy steps:-

  1. Create a NSObject File with named "GlobalVars.h and .m" or as u wish

  2. Declare your global variable in GlobalVars.h file after #import and before @implementation like-

    extern NSString *Var_name;

  3. initialize it in GlobalVars.m file after #import and before @implementation like-

    NSString *Var_name = @"";

  4. Define its property in AppDelegate.h File

    @property (nonatomic, retain) NSString *Var_name;

  5. synthesize it in AppDelegate.m File like-

    @synthesize Var_name;

  6. Now where you want to use this variable (in .m file) just import/inclue GlobalVars.h file in that all .h files, and you can access or can changes easily this variable.

  7. Carefully follow these Steps and it'll work Surely.

Upvotes: 2

PfhorSlayer
PfhorSlayer

Reputation: 1366

Single source file:

int myGlobal;

Header file:

extern int myGlobal;

Any file including the header:

myGlobal = 10;

Upvotes: 1

Williham Totland
Williham Totland

Reputation: 29009

On a related note; global variables are (very) generally speaking considered a Bad Thing™. In Obj-C the more common approach is making them a property on a singleton object, ensuring at least some encapsulation is taking place.

In an AppKit/UIKit application; a global variable might more properly be a property on your application delegate; another, somewhat more involved, option is making a singleton class for encapsulating the variable and related methods.

Upvotes: 2

philsquared
philsquared

Reputation: 22493

Just the same way that you would in C. Are you having any particular problem?

Upvotes: 3

Related Questions