开发者

iPhone Global Variable?

开发者 https://www.devze.com 2023-01-14 07:31 出处:网络
I have two views with their own .h and .m files开发者_StackOverflow社区 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?

I have two views with their own .h and .m files开发者_StackOverflow社区 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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消