0

This my be the strangest error I've ever seen.
I'm creating a maze game that loads levels from text files, but if the file has more than three rows, it seems to randomly change most of my variables. I load in a text file then run through the lines and create an object at the proper location based on its letter.
Any advice?

Text File:
TTTTTTTTTTTTTTTTT
TTTTTTTTTTTTTTTTT
TTTTTTTTTTTTTTTTT
TTTTTRPPGPPDTTTTT
TTTTTPTPTPTPTTTTT
TTTTTPPPWPPPTTTTT
TTTTTPTPPPTPTTTTT
TTTTTPPPTPPPTTTTT
TTTTTPTPPPTPTTTTT
TTTTTUPPPPPLTTTTT
TTTTTTTTPTTTTTTTT
TTTTTTTTBTTTTTTTT
TTTTTTTTPTTTTTTTT

NSString *path = [[NSBundle mainBundle] pathForResource:@"map2c" ofType:@"txt"];
NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];
NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\r\n"]];
int y  = 0;
for (NSString* line in lines) {

    NSString* ty = @"TBGWUDLRP";
    char *str = (char *)[line UTF8String];
    char *str2 = (char*)[ty UTF8String];
    grannyMoving = 2;
    int x = str2[0];
    char x2 = str2[1];
    char GrannyStr = str2[2];
    char wolfStr = str2[3];

    char UpStr = str2[4];
    char DownStr = str2[5];
    char leftStr = str2[6];
    char rightStr = str2[7];
    char PathStr = str2[8];
    y--;
    maxY = y;
    if (line.length) {
        maxI = line.length;
        for (int i = 0; i< line.length; i++) {                
 SKSpriteNode* tree = [SKSpriteNode spriteNodeWithImageNamed:@"tree3"];
            tree.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(31, 31)];
            tree.physicsBody.affectedByGravity = false;
            tree.physicsBody.dynamic = NO;
            tree.position = CGPointMake(64*i+20, 64*y+800);
            tree.zPosition = -1* tree.position.y;
Justin Buergi
  • 131
  • 11

1 Answers1

0

From the documentation:

This C string is a pointer to a structure inside the string object, which may have a lifetime shorter than the string object and will certainly not have a longer lifetime. Therefore, you should copy the C string if it needs to be stored outside of the memory context in which you use this property.

To fix this you have to make a copy of the characters returned by UTF8String. This answer provides two solutions.

Community
  • 1
  • 1
CodeSmile
  • 64,284
  • 20
  • 132
  • 217