// 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];
我不能在这两种方法中做两次,因此如何做到这一点?
答案 0 :(得分: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"]);
}
答案 1 :(得分: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-----