iPhone全局变量? [英] iPhone Global Variable?

查看:99
本文介绍了iPhone全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个视图,当然有自己的.h和.m文件。如何在一个视图中声明一个bool(或任何变量),并打包在另一个视图中访问它?



谢谢。

$ b Objective-C是一个普通的ANSI C的超集,所以你可以创建和使用全局变量,就像在老式的C中一样。

p>

在一个.m或.c文件中,放:

  BOOL gMyGlobalBoolVar = NO; //或者YES,这取决于需要的任何初始状态

我可能会把它们放在一个集中的单例类,比如你的appdelegate .m文件,或者单独的.c文件,比如myGlobals.c。我通常将这些放置在#imports / includes之后,但在任何类,方法或函数定义之前,以阐明它们可以在任何对象或函数之外访问。



所有你想访问gMyGlobalBoolVar的类的.h文件,放:

  extern BOOL gMyGlobalBoolVar; 

然后只需在课程中的任何地方使用它们:

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

全局变量的使用目前不是政治上正确的,但是对于快速代码,你永远不会尝试发布,重用,扩展或寻找粗糙的bug,它们的工作方式很好,就像他们在几乎所有计算机和编程语言中的工作一样,从50年前开始。


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.

解决方案

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.

这篇关于iPhone全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆