how to declare a variable as extern in objectivec,so that i can access that in any view controller

StackOverflow https://stackoverflow.com/questions/3409350

  •  25-09-2019
  •  | 
  •  

Question

i want to access the same variable in all view controllers ....

Was it helpful?

Solution

extern is a C keyword, and works the same in Objective-C as in straight C. In your header file, declare your variable:

extern NSString *myGlobal;

And then set it in your .m file.

However, this is frequently a poor coding practice; it is generally preferable to explicitly hand your view controllers some kind of state object or data source.

OTHER TIPS

Instead of putting in an extern for variables, store your data in the AppDelegate instance - or in some other singleton. Then you can get to it, and modify it, from anywhere.

While I'll admit I still use the AppDelegate solution quite often, I believe the singleton design pattern is a better solution. Here's a link to a solution and the reasoning.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top