我正在尝试使用objectA创建一个NSMutableDictionary(dictA)。当我尝试查看我的字典(NSLog)时,每个键都指向同一个地址。我有一个objectA_1,它是objectA类型,用于设置字典。此外,如果我尝试getObject,我总是得到添加到字典中的最后一个键/值。我尝试了setValue并获得了相同的结果。我的objectA有问题吗?释放方法不正常吗?我不应该保留吗?谢谢。
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";
答案 0 :(得分:1)
我假设你的意思是:
objectA *objectA_1 = [[objectA alloc] init];
您应该只释放一次对象。这是因为每次字典删除元素时,它都会自动调用对象的释放,因为每次将它添加到字典时它都会自动保留对象。
请尝试使用此代码:
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];
此外,您需要实现自定义对象的description
方法,以便NSLog知道如何打印它。