views:

262

answers:

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

My question is since both methodA and methodB are using the NSDictionary object [i.e dictobj] In which method should i write this code:

dictobj = [[NSDictionary alloc]init];

I can't do it twice in both methods, hence how to do it golbally?

+1  A: 

First of all, if you need to modify contents of the dictionary, it should be mutable:

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

You typically create instance variables like dictobj in the designated initializer like this:

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

and free the memory in -dealloc:

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

You can access your instance variables anywhere in your instance implementation (as opposed to class methods):

-(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"]);
}
Costique
i tried using init method, nut stil its in vain :( ... i'm not able to access the contents of dictionary in methodB,but in methodA i'm able to access it.When i try to print the objectForKey in methodB, its returning me null.
suse
What are you doing in those methods exactly? It looks like you either declare a method-local variable which shadows your ivar or just reset the ivar. I've updated the sample above to better illustrate what I'm talking about.
Costique
A: 
-----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-----
EEE
i did it.. but its local again. . when i try to access in methods, it gives an error saying dictobj undeclared
suse
As Dave DeLong said the attemp you are making is different than glbal variables but instance variables. I am updating my answer for global varible.
EEE