开发者

how to declare a global variable in Objective-C?

// 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 ob开发者_如何学Gojects 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?


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"]);
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜