user2970535
user2970535

Reputation: 91

How to access outside class variable data in Objective-C?

I have a header file With NSMutableDictionary varibale and a function as follows

#import <Foundation/Foundation.h>
@interface Client : NSObject{}; 
@property (assign)NSMutableDictionary *dict;
- (NSMutableDictionary *)myDict;
@end

In .m File

@implementation Client
{
NSMutableDictionary *dict;//=[[NSMutableDictionary alloc]initWithCapacity:10];
}
-(NSMutableDictionary *):myDict{
return dict;
}

My Question is Where I have to Initialize dict? so that I can access it from anywhere in my project by using something like Client.myDict . (It has to return all key value pair)

Upvotes: 1

Views: 604

Answers (1)

Rob
Rob

Reputation: 438477

You are defining a method, myDict to retrieve the value of dict property. But when the compiler synthesizes that property, it will automatically synthesize a dict getter method, so there's no need for the myDict method. You can just remove that.

Generally you'd do something like this:

#import <Foundation/Foundation.h>

@interface Client : NSObject
@property (nonatomic, strong) NSMutableDictionary *dict;
@end

Note, no braces and no semicolon on the @interface line.

And, in answer to your question about how to initialize the property (or, technically, the synthesized instance variable), you do that in your classes' init method:

@implementation Client

- (id)init
{
    self = [super init];
    if (self) {
        _dict = [[NSMutableDictionary alloc] init];
    }

    return self;
}

@end

Note, no explicitly declared instance variable needed, as the compiler will synthesize one for you (with a leading underscore). Also, no "getter" method needs to be written, either, as the compiler will synthesize that for you as well.

If you were using ARC (and I hope you are), you'd replace that assign with strong, as I did above. But if you weren't using ARC, you'd leave it as retain, but then you'd have to write a dealloc method (but do not write this if you have ARC):

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

You can then use this class like so:

Client *client = [[Client alloc] init];
[client.dict addObject:@"One"];

// you can access it this way

NSLog(@"client.dict = %@", client.dict);

// or this way

NSLog(@"[client dict] = %@", [client dict]);

Upvotes: 1

Related Questions