Aryan Kashyap Aryan Kashyap - 5 months ago 10
iOS Question

Not creating a new instance of NSMutableDictionary when passing to another class

i have an NSMutableDictionary declared in a class but i want to print get access to the contents of it in another class for example

@interface MyClass0 : NSObject
{

}

@property (nonatomic, strong) NSMutableDictionary *valuee;
@end


and in implementation i do

@implementation MyClass0

- (void)viewDidLoad{
[super viewDidLoad];

[valuee setObject:@"name" forKey:@"Aryan"];

}

@end


Now i create a new class called MyClass1 where i want to access these

@interface MyClass1 : NSObject
{
}

@property (nonatomic, strong) NSMutableDictionary *dict;

@end


and the implementation

@implementation MyClass1
@synthesize dict;

- (void)viewDidLoad{
[super viewDidLoad];

self.dict = [[NSMutableDictionary alloc] init];
MyClass0 *c = [[MyClass0 alloc] init];

self.dict = c.valuee;

// dict is not nil but the contents inside is nil so it clearly creates a new instance


}

@end

Answer

You are creating the instance of MyClass0 and valuee is declared but not initialized.

The closest solution to your code is

MyClass0 *c = [[MyClass0 alloc] init];
c.valuee = [[NSMutableDictionary alloc] init];

self.dict = c.valuee;

If a value is assigned to a declared property then an explicit initialization is not necessary.