In apps, Plist files are often used for data storage!

  • A. Plist File in the application package

    NSString * path = [[NSBundle mainBundle]pathForResource:@”RankList.plist” ofType:nil]; NSArray * plistArray = [[NSArray alloc] initWithContentsOfFile:path]; for (NSDictionary * dict in plistArray) { [self.dataArray addObject:dict]; }

Create:

Note: The plist files in the application package can only read data! Cannot write data!

**[NSBundle mainBundle]** Files in the obtained path cannot be modified

NSString * path = [[NSBundle mainBundle] pathForResource:@"gg.plist" ofType:nil]; NSDictionary * plistDict = [[NSDictionary alloc] initWithContentsOfFile:path]; NSLog(@"plistDict:%@",plistDict); NSDictionary * addDict = @{ @"score":@"123", @"name":@"adama" }; If ([addDict writeToFile:path atomically:YES]) {NSLog(@" Save array as attribute list file successfully!!" ); NSDictionary * plistDict = [[NSDictionary alloc] initWithContentsOfFile:path]; NSLog(@"plistDict:%@",plistDict); }else{NSLog(@" Saving array as property list file failed "); }Copy the code

Print effect:

2017-08-26 10:03:31.734 plistDict:{} 2017-08-26 10:03:31.735 plistDict:{} 2017-08-26 10:03:31.735 plistTest[16:54082] Saving array as property list file succeeded!! 735 plistTest[164:54082] plistDict:{name = Ada; score = da; }Copy the code

Display storage success! But it doesn’t work! The plist file is always the same:

  • B. “Plist File” in sandbox

    NSArray *sandboxpath= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [sandboxPath objectAtIndex:0]; / / the documents path nsstrings * plistPath = [documentsDirectory stringByAppendingPathComponent: @ “RankList. Plist”]. NSArray * plistDataArray = [[NSArray alloc] initWithContentsOfFile:plistPath]; for (NSDictionary * dict in plistDataArray) { [self.dataArray addObject:dict]; }

## leaderboards are implemented due to deletion, addition, and modification of data (considering the existence of Plist files?). So the Plist file chooses to create and use the following global variables in the sandbox:

NSString * _jifenStr; NSString * _nameStr; // User name int _indexWhereAdd; // Insert positionCopy the code

Operation steps:

NSArray *sandboxpath= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [sandboxPath objectAtIndex:0]; / / sandbox document path, put the file nsstrings * plistPath = [documentsDirectory stringByAppendingPathComponent: @ "RankList. Plist"]. // Plist file path BOOL hasTheRightPlist = NO; // Check whether the plist file NSFileManager * fileManger = [NSFileManager defaultManager]; / / file management class NSArray * dirArray = [fileManger contentsOfDirectoryAtPath: documentsDirectory error: nil]; If ([STR isEqualToString:@" ranklist.plist "]) {if (STR isEqualToString:@" ranklist.plist "]) { // Contains "ranklist. plist" hasTheRightPlist = YES; }} if (hasTheRightPlist == YES) {// Sandbox document path contains "ranklist. plist" file NSArray * plistArray = [[NSArray alloc] initWithContentsOfFile:plistPath]; for (int i = 0; i < plistArray.count; i++) { NSDictionary * dict = plistArray[i]; If ([_jifenStr integerValue] > [dict[@"score"] integerValue]) {// Greater than UIAlertView * alertV = [[UIAlertView alloc] initWithTitle:@" Submit score "message:@" Congratulations on getting into the leaderboard" Delegate :self cancelButtonTitle:nil OtherButtonTitles :@" confirm ", nil]; [alertV setAlertViewStyle:UIAlertViewStylePlainTextInput]; UITextField * textName = [alertV textFieldAtIndex:0]; Textname. placeholder = @" Please input your name "; textName.clearButtonMode = UITextFieldViewModeWhileEditing; [alertV show]; alertV.tag = 0; _indexWhereAdd = i; break; } else {// less than if (I == plistarray. count-1 && plistarray. count < 10) {// The last && does not exceed the leaderboard limit UIAlertView * alertV = [[UIAlertView alloc] initWithTitle:@" Submit score "message:@" Congratulations on getting into the leaderboard" Delegate :self cancelButtonTitle:nil OtherButtonTitles :@" confirm ", nil]; [alertV setAlertViewStyle:UIAlertViewStylePlainTextInput]; UITextField * textName = [alertV textFieldAtIndex:0]; Textname. placeholder = @" Please input your name "; textName.clearButtonMode = UITextFieldViewModeWhileEditing; [alertV show]; alertV.tag = 1; _indexWhereAdd = i; break; }}}} else {UIAlertView * alertV = [[UIAlertView alloc] initWithTitle:@" Submit score "message:@" Congratulations on getting into the leaderboard" delegate:self CancelButtonTitle :nil otherButtonTitles:@" confirm ", nil]; [alertV setAlertViewStyle:UIAlertViewStylePlainTextInput]; UITextField * textName = [alertV textFieldAtIndex:0]; Textname. placeholder = @" Please input your name "; textName.clearButtonMode = UITextFieldViewModeWhileEditing; [alertV show]; alertV.tag = 2; // Create a plist file if there is no plist file.Copy the code

UIAlertView protocol: Stores user data

#pragma mark - UIAlertViewDelegate -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  { UITextField * textNameTF = [alertView textFieldAtIndex:0]; _nameStr = textNameTF.text; If (buttonIndex == 0 && _namestr.length > 0) {// Confirm button NSArray * sandboxPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [sandboxPath objectAtIndex:0]; NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"RankList.plist"]; NSArray * plistArray = [[NSArray alloc] initWithContentsOfFile:plistPath]; NSMutableArray * addToPlistArr; If (plistArray) {addToPlistArr = plistarray.mutablecopy; } else {// Plist array does not exist addToPlistArr = @[]. } NSDictionary * addDict = @{ @"score":_jifenStr, @"name":_nameStr }; switch (alertView.tag) { case 0:{ [addToPlistArr insertObject:addDict atIndex:_indexWhereAdd]; If (addtoplistarr.count > 10) {// if (addToPlistArr removeObjectAtIndex:(addtoplistarr.count -1)]; } if ([addToPlistArr writeToFile:plistPath atomically:YES]) {NSLog(@" Save array as attribute list file successfully!!" ); }else{NSLog(@" Saving array as property list file failed "); } }break; case 1:{ [addToPlistArr addObject:addDict]; If ([addToPlistArr writeToFile:plistPath atomically:YES]) {NSLog(@" Save array as attribute list file successfully!!" ); }else{NSLog(@" Saving array as property list file failed "); } }break; Case 2:{// The plist file does not exist in the directory ❤️❤️❤️. If you add the plist file directly, add the plist file ❤️❤️❤️ [addToPlistArr addObject:addDict]. If ([addToPlistArr writeToFile:plistPath atomically:YES]) {NSLog(@" Save array as attribute list file successfully!!" ); }else{NSLog(@" Saving array as property list file failed "); } }break; default: break; } else {MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; hud.mode = MBProgressHUDModeText; Hud. Label. text = @" Select obscure, score not saved "; hud.margin = 10.f; hud.offset = CGPointMake(0, -60.f); hud.removeFromSuperViewOnHide = YES; [hud hideAnimated: YES afterDelay: 1.5 f]; } //NSLog(@"%ld",buttonIndex); }Copy the code

logic

Check whether the ranklist. plist file exists in the directory.

  • Not included: Create “ranklist. plist” file (Array :Array) and add an object information (Dictionary :Dictionary)

  • Contains: Sort stored data (integral: _jifenStr)

    • Data larger than any element (object information) in the ranklist. plist file (Array :Array) : directly inserted into the corresponding location.

      If the number of arrays exceeds the limit (10) after inserting data, remove the last element.

    • No more than any element in the ranklist. plist file (Array :Array) :

      • If the number of arrays exceeds the upper limit (10), no processing is performed

      • The number of arrays does not exceed the limit (10) : The array is added directly to the end of the array




(2017.08.26)

goyohol’s essay