2010-02-17 37 views
1
// MyClass.h 
@interface MyClass : NSObject 
{ 
    NSDictionary *dictobj; 
} 
@end 

//MyClass.m 
@implementation MyClass 

-(void)applicationDiDFinishlaunching:(UIApplication *)application 
{ 

} 
-(void)methodA 
{ 
// Here i need to add objects into the dictionary 
} 

-(void)methodB 
{ 
//here i need to retrive the key and objects of Dictionary into array 
} 

我的问题是,因为两个和了methodA的methodB正在使用的NSDictionary对象[即dictobj]在该方法中,我应该写这样的代码:如何在Objective-C中声明一个全局变量?

dictobj = [[NSDictionary alloc]init]; 

在两种方法我不能做两遍,因此如何在全球范围内做到这一点?

+1

这不是一个全局变量。这是一个实例变量。全局变量只存在于整个应用程序的一个位置。一个实例变量存在于其包含的类的每个实例中。 –

+0

你是对的.... – suse

回答

2

首先,如果你需要修改词典的内容,它应该是可变的:

- (id) init 
{ 
    [super init]; 
    dictobj = [[NSMutableDictionary alloc] init]; 
    return self; 
} 

@interface MyClass : NSObject 
{ 
    NSMutableDictionary *dictobj; 
} 
@end 

通常,您可以在指定初始化像这样创建一个像dictobj实例变量

并释放内存中的内存:-dealloc:

- (void) dealloc 
{ 
    [dictobj release]; 
    [super dealloc]; 
} 

您可以访问哟乌尔实例变量在您的实例执行的任何地方(而不是类方法):

-(void) methodA 
{ 
    // don't declare dictobj here, otherwise it will shadow your ivar 
    [dictobj setObject: @"Some value" forKey: @"Some key"]; 
} 

-(void) methodB 
{ 
    // this will print "Some value" to the console if methodA has been performed 
    NSLog(@"%@", [dictobj objectForKey: @"Some key"]); 
} 
+0

我尝试使用初始化方法,坚果stil其徒劳:(......我无法访问methodB中的字典的内容,但在methodA我能够访问它。 当我尝试在methodB中打印objectForKey时,它返回null。 – suse

+1

你在做那些方法到底是什么?看起来你要么声明一个方法局部变量来影响你的ivar或者只是重置ivar。我更新了上面的示例以更好地说明我在说什么 – Costique

0
-----AClass.h----- 
extern int myInt; // Anybody who imports AClass.h can access myInt. 

@interface AClass.h : SomeSuperClass 
{ 
    // ... 
} 

// ... 
@end 
-----end AClass.h----- 


-----AClass.h----- 
int myInt; 

@implementation AClass.h 
//... 
@end 
-----end AClass.h----- 
+0

我做了它但是它的本地当我尝试访问方法时,它给出了一个错误,说dictobj未声明 – suse

+1

正如Dave DeLong所说的尝试你我正在更新我的全球变数的答案 – EEE

+0

我想EEE的意思是写在最后一部分是'AClass.m',n Ø?你还需要'#import'AClass.h“'然后才能访问并修改'int',否? –