2014-10-18 66 views
0

這是我見過的最奇怪的錯誤。
我正在創建一個從文本文件加載級別的迷宮遊戲,但如果該文件有三行以上,它似乎會隨機更改大部分變量。我加載一個文本文件,然後運行這些代碼,並根據它的字母在適當的位置創建一個對象。
有什麼建議嗎?從文件中讀取文本的XCODE擦除變量

文本文件:
TTTTTTTTTTTTTTTTT
TTTTTTTTTTTTTTTTT
TTTTTTTTTTTTTTTTT
TTTTTRPPGPPDTTTTT
TTTTTPTPTPTPTTTTT
TTTTTPPPWPPPTTTTT
TTTTTPTPPPTPTTTTT
TTTTTPPPTPPPTTTTT
TTTTTPTPPPTPTTTTT
TTTTTUPPPPPLTTTTT
TTTTTTTTPTTTTTTT Ť
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; 

回答

0

documentation

此C字符串是一個指向字符串對象, 內部的結構,其可具有壽命比字符串對象短和 肯定不會有更長的使用壽命。因此,如果需要將C 字符串存儲在您使用此屬性的內存上下文之外( ),則應複製C 字符串。

要解決這個問題,你必須複製UTF8String返回的字符。 This answer提供了兩種解決方案。

+0

被重置的變量不僅僅是這些,而且甚至在此之前設置的屬性,包括skivation – 2014-11-05 21:35:51

+0

也爲我分配的變量獲取exc_bad_access – 2014-11-05 21:39:32