Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Objective-C中声明全局变量?_Objective C_Global Variables_Nsdictionary - Fatal编程技术网

如何在Objective-C中声明全局变量?

如何在Objective-C中声明全局变量?,objective-c,global-variables,nsdictionary,Objective C,Global Variables,Nsdictionary,我的问题是,因为methodA和methodB都在使用NSDictionary对象[即dictobj],我应该用哪种方法编写代码: // MyClass.h @interface MyClass : NSObject { NSDictionary *dictobj; } @end //MyClass.m @implementation MyClass -(void)applicationDiDFinishlaunching:(UIApplication *)application {

我的问题是,因为methodA和methodB都在使用NSDictionary对象[即dictobj],我应该用哪种方法编写代码:

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

这两种方法我都做不到两次,因此如何做到最好?

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

dictobj = [[NSDictionary alloc]init];
通常在指定的初始值设定项中创建dictobj等实例变量,如下所示:

@interface MyClass : NSObject
{
    NSMutableDictionary *dictobj;
}
@end
并在-dealloc中释放内存:

- (id) init
{
    [super init];
    dictobj = [[NSMutableDictionary alloc] init];
    return self;
}
您可以在实例实现中的任何位置访问实例变量(与类方法相反):


这不是一个全局变量。这是一个实例变量。在整个应用程序中,全局变量仅存在于一个位置。实例变量存在于其包含类的每个实例化中。。但它又是本地的。当我尝试访问in方法时,它给出了一个错误,说dictobj undeclaredAs Dave DeLong说您正在进行的尝试与glbal变量不同,但与实例变量不同。我正在更新关于全局变量的答案。我认为EEE的意思是在最后一部分中编写
AClass.m
,不是吗?您还需要导入“AClass.h”,然后才能访问和更改
int
,否?我尝试使用init方法,但仍然徒劳:(…我无法在methodB中访问dictionary的内容,但在methodA中我可以访问它。当我尝试在methodB中打印objectForKey时,它返回我null。您在这些方法中到底在做什么?看起来您要么声明一个覆盖ivar的方法局部变量,要么只是重置ivar。我已经更新了示例以更好地说明我所说的。
- (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"]);
}
-----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-----