我的字典返回内存地址而不是实际值,intValue强制转换不工作 - objective-C

时间:2011-01-26 17:19:48

标签: iphone objective-c

我已经看到了一些类似的问题,但大多数建议的修复对我不起作用。

当我的游戏启动时,它调用一个方法,读取我的Plist以找到关键字“gameProgress”,如果这是第一次运行游戏,它会创建Plist并添加关键字“gameProgress”及其值0。 它看起来像这样:

else {
  // create it
  NSLog(@"dictionary didn't exist, creating...");
  dict = [NSMutableDictionary dictionaryWithCapacity:30];

  // create a NSNumber object containing the
  // integer value 0 and add it as 'gameProgress' to the dictionary.
  NSNumber *numberOfCompletedLevels = [NSNumber numberWithInt:0];
  [dict setObject:numberOfCompletedLevels forKey:@"gameProgress"];

  // write dictionary to Documents directory...
  NSLog(@"writing to %@...", plistPath);
  [dict writeToFile:plistPath atomically:YES];
 }
 [self setLevelsCompleted:[[dict objectForKey:@"gameProgress"]intValue]];
 NSLog(@"levels completed is now: %i "), levelsCompleted; 

 // show the contents of the dictionary in the console
 NSLog(@"dictionary values...:");
 for (id key in dict) {
  NSLog(@"key=%@, value=%@", key, [dict objectForKey:key]);
 }
有趣的是,当代码运行时,第一个NSLog告诉我它将“levelsCompleted”变量设置为1026944,但是当我打印字典的内容时,它告诉我“gameProgress”的值是0.

显然出现了问题,并且intValue无法正常工作,我尝试使用(int)转换,但是再次不成功。

有没有人有想法?

提前谢谢你 问候 彼得

2 个答案:

答案 0 :(得分:2)

您写道:NSLog(@"levels completed is now: %i "), levelsCompleted

, levelsCompleted应该放在括号内。事实上,你并没有传递一个参数来跟%i一起使用,并且它正在抓住恰好位于争论所在位置的随机垃圾。

顺便提一下,此代码有效(虽然不正确)的原因是因为,在参数列表之外,逗号是运算符。它执行左侧的东西,丢弃它的值并返回右侧的东西的值。

答案 1 :(得分:0)

我已经尝试了你的代码,似乎没有问题,

// create a NSNumber object containing the // integer value 0 and add it as 'gameProgress' to the dictionary. 
NSNumber *numberOfCompletedLevels = [NSNumber numberWithInt:0];
[dict setObject:numberOfCompletedLevels forKey:@"gameProgress"];

int levelsCompleted = [[dict objectForKey:@"gameProgress"]intValue];
NSLog(@"levels completed is now: %i ", levelsCompleted);

// show the contents of the dictionary in the console 
NSLog(@"dictionary values...:"); 
for (id key in dict)
{ 
    NSLog(@"key=%@, value=%@", key, [dict objectForKey:key]); 
}

控制台输出

2011-01-26 22:30:54.532 Practice[8809:207] dictionary didn't exist, creating...
Current language:  auto; currently objective-c
2011-01-26 22:30:56.187 Practice[8809:207] levels completed is now: 0 
2011-01-26 22:30:56.362 Practice[8809:207] dictionary values...:
2011-01-26 22:30:57.015 Practice[8809:207] key=gameProgress, value=0

您的班级对象“levelsCompleted”可能有问题,请检查它是否不是NSNumber。

但是休息看起来很好......