Reputation: 31
I am using a series of code to read Plist file in my app, However a weird behavior kicks in. Here is an example of the code.
//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];
As it've shown, i've set up NSLog to keep watch of the value. Here is the log
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
They seems to reset themselves back to zero. The best i could get so far is it might be the for loop is causing this up since both logs have gotten printed twice( Seems like it runs a second loop and reset it.) Any idea what's wrong?
Example code of my 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>
Upvotes: 0
Views: 91
Reputation: 17012
You're confusing fast enumeration with an NSEnumerator
.
Either use NSEnumerator and loop over it using while ((object = [enumerator nextObject])) {
, or use fast enumeration on the level
object (no need to make an NSEnumerator
).
To try the latter strategy (recommended), replace this:
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);
}
with:
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);
}
Does that work?
See also this question.
Upvotes: 1