简体   繁体   English

如何使3 bool全局变量?

[英]How to make 3 bool global variable?

I'm creating a word game and I need to assign coins to a user: 我正在创建一个文字游戏,我需要向用户分配硬币:

firstly I've read over and over on subjects "Global variables" Unfortunately i'm not able to successfully do them. 首先,我一遍又一遍地阅读了“全局变量”主题。不幸的是,我无法成功完成它们。

I need to make 3 bool global variable such as btn1Pressed,btn2Pressed,btn3Pressed. 我需要使3布尔全局变量,如btn1Pressed,btn2Pressed,btn3Pressed。 & how to make the word "coins" global of type int as well? 以及如何使“ coins”一词成为int类型的全局变量? How is this done? 怎么做?

@interface MainView : 

使用关键字“ extern”可以使变量成为全局变量。

extern int coins = 9001; //over nine thousand!

If you mean "globals" as in "accessible everywhere in your app", you can use singletons: 如果您将“全局变量”表示为“可在应用程序中的任何位置访问”,则可以使用单例:

http://www.galloway.me.uk/tutorials/singleton-classes/ http://www.galloway.me.uk/tutorials/singleton-classes/

This way you can group all such global variables in one global object. 这样,您可以将所有此类全局变量组合在一个全局对象中。

To declare global variables, you need to declare them outside of any class definition. 要声明全局变量,您需要在任何类定义之外声明它们。 If I have a lot of global variables, I usually put them in their own source file and call it globals.m to help keep things organized. 如果我有很多全局变量,我通常将它们放在自己的源文件中,并将其命名为globals.m以帮助使事情井井有条。 If I only have one or two, I just declare them in the App delegate (after the #includes but before the @implementation). 如果只有一个或两个,则只需在App委托中声明它们(在#includes之后但@implementation之前)。

int coins;
BOOL btn1Pressed;
BOOL btn2Pressed;
BOOL btn3Pressed;
// etc

Then you declare them in a common header (I use globals.h) as extern . 然后,您在一个通用标头(我使用globals.h)中将它们声明为extern Declare them outside of any class definition: 在任何类定义之外声明它们:

extern int coins;
extern BOOL btn1Pressed;
extern BOOL btn2Pressed;
extern BOOL btn3Pressed;
...

That tells the compiler that "this variable is declared elsewhere", so it knows to resolve it at link time. 这告诉编译器“此变量在其他地方声明”,因此它知道在链接时解析它。 Include that header in any source module that needs access to those variables. 将该标头包含在需要访问这些变量的任何源模块中。

Using Singleton pattern is the ideal way to do it. 使用Singleton模式是理想的方法。

Create your properties in YourAppdelegate.h file for your bools btn1Pressed,btn2Pressed,btn3Pressed.Further synthesize them in YourAppdelegate.m file. 在YourAppdelegate.h文件中为布尔btn1Pressed,btn2Pressed,btn3Pressed创建属性。进一步在YourAppdelegate.m文件中合成它们。

Now if you want to access or change these values in any other classes 现在,如果要访问或更改其他任何类中的这些值

// Accessing btn1Value
   BOOL checkTheValueOFButton1 =   [(YourAppDelegate *)[UIApplication sharedApplication]btn1Pressed];

If you want to change the value 如果要更改值

 [(YourAppDelegate *)[UIApplication sharedApplication]setbtn1Pressed:NO];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM