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] 我应该在哪个方法中编写此代码:

dictobj = [[NSDictionary alloc]init];

我不能在这两种方法中做两次,因此如何做呢?

4

2 回答 2

2

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

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

您通常在指定的初始化程序中创建像 dictobj 这样的实例变量,如下所示:

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

并释放 -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"]);
}
于 2010-02-17T06:40:25.673 回答
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-----
于 2010-02-17T07:03:50.357 回答