我正在使用一系列代码在我的应用程序中读取Plist文件,但是一个奇怪的行为开始了。这是一个代码示例。
//init loading from PLIST here, and then associate value.
NSString *pathString=[NSString stringWithFormat:@"%@Levels",targetWorld];
NSString *path = [[NSBundle mainBundle] pathForResource:pathString ofType:@"plist"];
NSString *levelNameNumber = [[NSString alloc] initWithFormat:targetLevel];
NSDictionary *levelsList = [[NSDictionary alloc] initWithContentsOfFile:path];
NSDictionary *level = [levelsList objectForKey:levelNameNumber];
NSEnumerator *levelFormations = [level objectEnumerator];
for( NSDictionary *worldSize in levelFormations )
{
worldWidth = [[worldSize objectForKey:@"width"] intValue];
worldHeight = [[worldSize objectForKey:@"height"] intValue];
NSLog(@"height is %d",worldHeight);
NSLog(@"width is %d",worldWidth);
}
[levelNameNumber release];
[levelsList release];
如图所示,我已经设置了NSLog来监视价值。这是日志
2012-05-09 21:14:38.313 CapNTail[361:10a03] height is 344
2012-05-09 21:14:38.315 CapNTail[361:10a03] width is 123
2012-05-09 21:14:38.324 CapNTail[361:10a03] height is 0
2012-05-09 21:14:38.326 CapNTail[361:10a03] width is 0
他们似乎将自己重置为零。到目前为止我能得到的最好的可能是for循环导致了这个问题,因为两个日志都打印了两次(好像它运行了第二个循环并重置它。)知道什么是错的吗?
我的plist的示例代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>level1</key>
<dict>
<key>worldSize</key>
<dict>
<key>width</key>
<integer>123</integer>
<key>height</key>
<integer>344</integer>
</dict>
<key>formation</key>
<dict>
<key>playerPosX</key>
<integer>0</integer>
<key>playerPosY</key>
<integer>0</integer>
</dict>
</dict>
答案 0 :(得分:1)
您将快速枚举与NSEnumerator
混淆。
使用NSEnumerator并使用while ((object = [enumerator nextObject])) {
对其进行循环,或在level
对象上使用快速枚举(无需创建NSEnumerator
)。
要尝试后一种策略(推荐),请将其替换为:
NSEnumerator *levelFormations = [level objectEnumerator];
for( NSDictionary *worldSize in levelFormations )
{
worldWidth = [[worldSize objectForKey:@"width"] intValue];
worldHeight = [[worldSize objectForKey:@"height"] intValue];
NSLog(@"height is %d",worldHeight);
NSLog(@"width is %d",worldWidth);
}
使用:
for( NSDictionary *worldSize in level )
{
worldWidth = [[worldSize objectForKey:@"width"] intValue];
worldHeight = [[worldSize objectForKey:@"height"] intValue];
NSLog(@"height is %d",worldHeight);
NSLog(@"width is %d",worldWidth);
}
这有用吗?