2011-11-18 35 views

回答

4

在一些非常特殊的情况下,真正的全局变量,这样事情就简单。我不认为你详尽研究的问题,但这里是我的答案,无论如何,一个简单的例子:


// 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 
 

现在,你可以使用globalVariable随时随地在你的代码,你甚至都不需要包括头文件。

警告:如果您需要线程安全性或不同的变量类型,事情会稍微复杂一些。

-2

您可以使用全局变量在你的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]; 
     } 

希望这将有助于

+0

感谢您的帮助,但noo变量的数据类型为整数 –

相关问题