user141302
user141302

Reputation:

correct method to create global variable in iphone sdk?

is there any best method to maintain global variable in iphone sdk? if i change it, it will affect in all controllers,views of that iphone application?

Upvotes: 0

Views: 568

Answers (2)

hotpaw2
hotpaw2

Reputation: 70673

Globals are currently considered ugly, but they are a type of unprotected pre-allocated pre-initialized singleton, and all there was in computer programming best practices 50 years ago (1st edition of Knuth's books, etc.). The best method of maintaining globals includes using a lot of very clear comments so that you can consider something else when it's time to make the code more modular and reusable (potentially at some cost in code size).

To answer the OP's question, if you modify a global, then any controllers or views (and any C or Objective C code in the same thread that doesn't "cover" the globals name) that reads that global will get the newest value. But that new value won't be "pushed" immediately. Those views or controllers won't notice any new value until some method eventually is called that actually reads the global variables.

If you need a view or controller to respond faster, then you will need notifications or key-value observing rather than just modifying a global variable.

Upvotes: 0

Dan Ray
Dan Ray

Reputation: 21893

Globals are ugly. Better to use a singleton "Data Manager" class that contains all your data, and then use either notifications or key-value observing to update your ViewControllers about changes.

Upvotes: 1

Related Questions