NSString读/写文件

时间:2010-08-02 18:47:31

标签: iphone objective-c cocos2d-iphone

我只是在读取和编写NSString到iphone上的dat文件时遇到了麻烦。

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *saveFile = [documentsDirectory stringByAppendingPathComponent:@"Profiles.dat"];
  Boolean saveFileExists = [[NSFileManager defaultManager] fileExistsAtPath:saveFile];

  // NSString *saveFile = [documentsDirectory stringByAppendingPathComponent:@"Profiles.dat"];


  NSMutableData *gameData;
  NSKeyedUnarchiver *decoder;

  NSKeyedArchiver *encoder;

  //decoder  = [[NSKeyedUnarchiver alloc] initForWritingWithMutableData:gameData];

  myGameState *gameState = [myGameState sharedMySingleton];


  if(saveFileExists) {
   gameData = [NSData dataWithContentsOfFile:saveFile];
   decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:gameData];

   gameState.Profile1 = [decoder decodeObjectForKey:@"Name1"];
   gameState.Profile2 = [decoder decodeObjectForKey:@"Name2"];
   gameState.Profile3 = [decoder decodeObjectForKey:@"Name3"];
   gameState.Profile4 = [decoder decodeObjectForKey:@"Name4"];
   gameState.Profile5 = [decoder decodeObjectForKey:@"Name5"];

   gameState.curProfile = [decoder decodeObjectForKey:@"curProfile"];
   [decoder release];


  }
  else {
   gameData = [NSMutableData data];
   encoder  = [[NSKeyedArchiver alloc] initForWritingWithMutableData:gameData];
   gameState.Profile1 = @"Default1";
   gameState.Profile2 = @"Default2";
   gameState.Profile3 = @"Default3";
   gameState.Profile4 = @"Default4";
   gameState.Profile5 = @"Default5";

   [encoder encodeObject:@"Default1" forKey:@"Name1"];
   [encoder encodeObject:@"Default2" forKey:@"Name2"];
   [encoder encodeObject:@"Default3" forKey:@"Name3"];
   [encoder encodeObject:@"Default4" forKey:@"Name4"];
   [encoder encodeObject:@"Default5" forKey:@"Name5"];

   gameState.curProfile = gameState.Profile1;
   [encoder encodeObject:gameState.curProfile forKey:@"curProfile"];

   [encoder finishEncoding];
   //[gameData writeToFile:<#(NSString *)path#> atomically:<#(BOOL)useAuxiliaryFile#>
   [gameData writeToFile:saveFile atomically:YES ];
   //[gameData writeToFile:saveFile atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];

   [encoder release];

  }

gameState.curProfile等都是NSString指针。现在我对Objective C非常新,似乎无法正常工作。我搜索过各种论坛,似乎无法找到正确的方法来做到这一点。我想要的只是读取一个NSString写入一个dat文件,但它不是按原样工作。我已经设法写了整数和bool没有问题,因为我自己无法解决文本问题。 任何帮助表示赞赏 谢谢 克

1 个答案:

答案 0 :(得分:1)

您的代码在这里没有任何问题。我猜你在代码的其他部分遇到了问题。

顺便说一句,如果您只需要保存一些条目,那么您不必自己完成所有这些工作;只需使用NSUserDefaults。它会自动准备文件以保存数据,对数据进行编码,并在下次启动时解码数据。见this Apple document。它可以用作

 [[NSUserDefaults standardUserDefaults] setString:@"boo" forKey:@"key!"];

以后可以将数据读作

 NSString* s=[[NSUserDefaults standardUserDefaults] stringForKey:@"key!"];

就这么简单!你可能想打电话

[[NSUserDefaults standardUserDefaults] synchronize];

强制将数据保存到文件中;通常这不是必要的(系统在退出时自动执行此操作等)