views:

111

answers:

1

I am trying to create a NSMutableDictionary(dictA) with objectA. When I try to view my dictionary(NSLog), each key is pointing to the same address. I have an objectA_1 which is type objectA and used to setup the dictionary. Also, if I try to getObject, I always get the last key/value that was added to the dictionary. I tried setValue and got the same results. Is there something wrong with my objectA? Is the release method not working properly? Am I retaining when I shouldn't? Thank you.

dictA = [[NSMutableDictionary alloc] init];
objectA *objectA = [[objectA alloc] init];

objectA.ID = 5;
[dictA setObject:objectA forKey:@"apple"];
[objectA release];

objectA.ID = 50;
[dictA setObject:objectA forKey:@"japan"];
[objectA release];

objectA.ID = 6;
[dictA setObject:objectA forKey:@"paris"];
[objectA release];

objectA.ID = 11;
[dictA setObject:objectA forKey:@"pizza"];
[objectA release];

//NSlog:

apple = "objectA: 0x175830";
japan = "objectA: 0x175830";
paris = "objectA: 0x175830";
pizza = "objectA: 0x175830";
+1  A: 

I'm assuming that you meant:

objectA *objectA_1 = [[objectA alloc] init];

You should only be releasing the object only one time. This is because every time the dictionary removes the element, it will automatically call release on the object, since it automatically retains the object every time you add it to the dictionary.

Try this code instead:

dictA = [[NSMutableDictionary alloc] init];
objectA *objectA_1 = [[objectA alloc] init];

[dictA setObject:objectA_1 forKey:@"apple"];
[dictA setObject:objectA_1 forKey:@"japan"];
[dictA setObject:objectA_1 forKey:@"paris"];
[dictA setObject:objectA_1 forKey:@"pizza"];
[objectA_1 release];

Additionally, you need to implement the description method of your custom object so that NSLog knows how to print it.

Senseful