iPhone Global Variable?

℡╲_俬逩灬. 提交于 2020-01-09 10:12:06

问题


I have two views with their own .h and .m files of course. How can I declare a bool (or any variable for that matter) in one view and be bale to access it in another view?

Thanks.


回答1:


Objective C is a superset of plain ANSI C, so you would create and use global variables exactly the same way as in old-fashioned C.

In exactly one .m or .c file, put:

BOOL gMyGlobalBoolVar = NO;  // or YES, depending on whatever initial state is needed

I might place these in a centralized singleton class, such as your appdelegate .m file, or in a separate .c file, such as myGlobals.c. I usually place these after the #imports/includes but before any class, method, or function definitions to clarify that they can be accessed outside of any object or function.

In the .h files for all classes where you want to access gMyGlobalBoolVar, put:

extern BOOL gMyGlobalBoolVar;

Then just use them anywhere in the class:

if ( [ self dogHasFleas ] ) { 
  gMyGlobalBoolVar = YES; 
}

The use of global variables is currently not "politically correct", but for quick code that you will never try to publish, reuse, extend, or hunt for gnarly bugs, they work just fine like they did in almost every computer and programming language from 50+ years ago.




回答2:


You can just take a reference to the view containing the bool and get the variable using a getter.

If you want app wide variables, you could put them in the AppDelegate, but I highly recommend against that since it tightly couples classes.




回答3:


Create a data model class. Instantiate it in your app delegate, and pass it along to your view controllers. Use Key-Value Observing to track changes to the model in your view controllers. See my answer here: How do I display and calculate numbers from a database on iPhone?

"Why shouldn't I use globals? It can't hurt just this once." This is a bad habit to get into. Avoiding global variables makes your code easier to read and reuse, easier to extend, and easier to debug.



来源:https://stackoverflow.com/questions/3601341/iphone-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!