我们如何在 Xcode 中创建整数类型的全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8180333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can we make a global variable of integer type in Xcode
提问by Amit Raj
How can I declare a global variable in Xcode and its data type should be integer and accessible by every class.
我如何在 Xcode 中声明一个全局变量,它的数据类型应该是整数并且每个类都可以访问。
回答by djromero
In some very special cases a truly global variable can simplify things. I don't think you researched the problem exhaustively, but here is my answer anyway, a simple case:
在一些非常特殊的情况下,一个真正的全局变量可以简化事情。我认为您没有详尽地研究这个问题,但无论如何,这是我的答案,一个简单的案例:
// Globals.h
#ifndef Globals_h
#define Globals_h
extern NSInteger globalVariable;
#endif
// main.m
NSInteger globalVariable;
int main(int argc, char *argv[])
{
globalVariable = <# initial value #>;
...
}
// Prefix.pch
#ifdef __OBJC__
#import
#import <Foundation/Foundation.h>
#import "Globals.h"
#endif
Now, you can use globalVariable
anywhere in your code, you don't even need to include the header file.
现在,您可以globalVariable
在代码中的任何位置使用,甚至不需要包含头文件。
Warning: things are slightly complex if you need thread safety or a different variable type.
警告:如果您需要线程安全或不同的变量类型,事情会稍微复杂一些。
回答by Alex Moskalev
You can use global variable in you AppDelegate :
您可以在 AppDelegate 中使用全局变量:
@interface myAppDelegate : NSObject <UIApplicationDelegate> {
MyDBManager *myDBManager;
}
@property (nonatomic, retain) MyDBManager *myDBManager;
@end
@interface AnyOtherClass : UITableViewController {
MyDBManager *myDBManager;
NSObject *otherVar;
}
@property (nonatomic,retain) MyDBManager *myDBManager;
@property (nonatomic,retain) NSObject *otherVar;
@end
//getting the data from "global" myDBManager and putting it into local var of AnyOtherClass
- (void)viewWillAppear:(BOOL)animated {
//get the myDBManager global Object
MyAppDelegate *mainDelegate = (MyAppDelegate *)[[UIApplication sharedApplication]delegate];
myDBManager = mainDelegate.myDBManager;
}
- (void)dealloc {
[otherVar release];
//[dancesDBManager release]; DO NOT RELEASE THIS SINCE ITS USED AS A GLOBAL VARIABLE!
[super dealloc];
}
Hope it will help
希望它会有所帮助