Saving the PLIST file data

To save data to PLIST, we will take a look at how to create a high score table and save the data of the highest score achieved by a player.

Getting ready

All the necessary files are already there because whackamole_template.plist was already added in the last section.

How to do it…

We will create three functions: one to load the high scores, the second to add the high scores, and the third to delete the scores in the file.

The function to load highScore is as follows. We will create two global variables—hiScores and hiScore—of the NSMutableArray type and int:

//** saving to PLIST
-(void) loadHiScores {

  //** Our template and file names
  NSString *templateName = @"whackamole_template.plist";
  NSString *fileName = @"whackamole.plist";

  //** Our dictionary
  NSMutableDictionary *fileDict;

  //** We get our file path
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *filePath = [documentsDirectorystringByAppendingPathComponent:fileName];

  if(![[NSFileManagerdefaultManager] fileExistsAtPath:filePath]){
    //** If file doesn't exist in document directory create a new one from the template

    fileDict = [NSMutableDictionarydictionaryWithContentsOfFile:getFileFromPath(templateName)];

  }else{

    //** If it does we load it in the dict
    fileDict = [NSMutableDictionarydictionaryWithContentsOfFile:filePath];

  }

  //** Load hi scores into our dictionary
  hiScores= [fileDictobjectForKey:@"hiscores"];

  //** Set the 'hiScore' variable (the highest score)

  for(id score in hiScores){
    intscoreNum = [[score objectForKey:@"score"] intValue];
    if(hiScore<scoreNum){

      hiScore = scoreNum;
    }
  }

  //** Write dict to file
  [fileDictwriteToFile:filePathatomically:YES];
  //** log out player names and scores
  for(id score in hiScores){

    NSMutableDictionary *scoreDict = (NSMutableDictionary*)score;

    NSLog(@"playerName: %@ , playerScore: %d",
      [scoreDictobjectForKey:@"name"],
      [[scoreDictobjectForKey:@"score"] intValue]);

  }


}

The function to add highScore to PLIST is as follows:

-(void) addHiScore {
  //** Our template and file names
  NSString *templateName = @"whackamole_template.plist";
  NSString *fileName = @"whackamole.plist";

  //** Our dictionary
  NSMutableDictionary *fileDict;

  //** We get our file path
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *filePath = [documentsDirectorystringByAppendingPathComponent:fileName];

  if(![[NSFileManagerdefaultManager] fileExistsAtPath:filePath]){

    //** If file doesn't exist in document directory create a new one from the template

    fileDict = [NSMutableDictionarydictionaryWithContentsOfFile:getFileFromPath(templateName)];
  }else{
    //** If it does we load it in the dict
    fileDict = [NSMutableDictionarydictionaryWithContentsOfFile:filePath];
  }

  //** Load hi scores into our dictionary
  hiScores = [fileDictobjectForKey:@"hiscores"];

  //** Add hi score
  boolscoreRecorded = NO;

  //** Add score if player's name already exists
  for(id score in hiScores){
    NSMutableDictionary *scoreDict = (NSMutableDictionary*)score;
    if([[scoreDictobjectForKey:@"name"] isEqualToString:currentPlayerName]){
    if([[scoreDictobjectForKey:@"score"] intValue] <currentScore){
      [scoreDictsetValue:[NSNumbernumberWithInt:currentScore] forKey:@"score"];
    }
    scoreRecorded = YES;
  }
}

//** Add new score if player's name doesn't exist
if(!scoreRecorded){
  NSMutableDictionary *newScore = [[NSMutableDictionaryalloc] init];
  [newScoresetObject:currentPlayerNameforKey:@"name"];
  [newScoresetObject:[NSNumbernumberWithInt:currentScore] forKey:@"score"];
  [hiScoresaddObject:newScore];
}

//** Write dict to file
[fileDictwriteToFile:filePathatomically:YES];

//** log out player names and scores
for(id score in hiScores){

  NSMutableDictionary *scoreDict = (NSMutableDictionary*)score;

  NSLog(@"playerName: %@ , playerScore: %d",
    [scoreDictobjectForKey:@"name"],
    [[scoreDictobjectForKey:@"score"] intValue]);

  }

}

Finally, the function to delete the entries is added as follows:

-(void) deleteHiScores {
  //** Our file name
  NSString *fileName = @"whackamole.plist";

  //** We get our file path
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *filePath = [documentsDirectorystringByAppendingPathComponent:fileName];

  //** Delete our file
  [[NSFileManagerdefaultManager] removeItemAtPath:filePatherror:nil];

  NSLog(@"Hi scores deleted!");

  hiScore = 0;
  [selfloadHiScores];
}

How it works…

To make it work, we will add the following code in the init function:

        //** saving data into a PLIST
        [selfloadHiScores];

        currentPlayerName = @"siddharth";
        currentScore = 24;

        [selfaddHiScore];
        [selfloadHiScores];


        [selfdeleteHiScores];

We will first load the high scores from the list.

Then, we will create two global variables—currentPlayerName and currentScore—of the NSString and int types, respectively.

Then, we will create a new player name and a new highScore variable. Then, we will add this data to PLIST, and then, we will load it again to make sure that the changes were made to the list.

Finally, we will delete the entries.

How it works…

As the PLIST template already has a name and score, it will be added along with the new data we added to PLIST.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.27.74