天天看點

iPhone開發教程之相關的plist檔案

建立.plist檔案并存儲

  NSString *errorDesc; //用來存放錯誤資訊

  NSMutableDictionary *rootObj = [NSMutableDictionary dictionaryWithCapacity:4]; //NSDictionary, NSData等檔案可以直接轉化為plist檔案

  NSDictionary *innerDict;

  NSString *name;

  Player *player;

  NSInteger saveIndex;

  for(int i = 0; i < [playerArray count]; i++) {

  player = nil;

  player = [playerArray objectAtIndex:i];

  if(player == nil)

  break;

  name = player.playerName;// This "Player1" denotes the player name could also be the computer name

  innerDict = [self getAllNodeInfoToDictionary:player];

  [rootObj setObject:innerDict forKey:name]; // This "Player1" denotes the person who start this game

  }

  NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:(id)rootObj format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDesc];

  這個plistData為建立好的plist檔案,用其writeToFile方法就可以寫成檔案。下面是代碼:

  /*得到移動裝置上的檔案存放位置*/

  NSString *documentsPath = [self getDocumentsDirectory];

  NSString *savePath = [documentsPath stringByAppendingPathComponent:@"save.plist"];

  /*存檔案*/

  if (plistData) {

  [plistData writeToFile:savePath atomically:YES];

  else {

  NSLog(errorDesc);

  [errorDesc release];

  - (NSString *)getDocumentsDirectory {

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

  return [paths objectAtIndex:0];

  4 讀取plist檔案并轉化為NSDictionary

  NSString *fullPath = [documentsPath stringByAppendingPathComponent:@"save.plist"];

  NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];

  5 讀取一般性文檔檔案

  NSString *tmp;

  NSArray *lines; /*将檔案轉化為一行一行的*/

  lines = [[NSString stringWithContentsOfFile:@"testFileReadLines.txt"]

  componentsSeparatedByString:@"\n"];

  NSEnumerator *nse = [lines objectEnumerator];

  // 讀取<>裡的内容

  while(tmp = [nse nextObject]) {

  NSString *stringBetweenBrackets = nil;

  NSScanner *scanner = [NSScanner scannerWithString:tmp];

  [scanner scanUpToString:@"<" intoString:nil];

  [scanner scanString:@"<" intoString:nil];