简体   繁体   中英

not able to save data into plist

I used one old example to save data into a plist.Data coming from plist is working fine but it's not changing or editing when I am trying to save data into a plist.even I am not getting any error massages.My code to save data is -

 -(void)saveData
 {
   // get paths from root direcory
   NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
   // get documents path
   NSString *documentsPath = [paths objectAtIndex:0];
   // get the path to our Data/plist file
   NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

  // set the variables to the values in the text fields
  personName = self.nameEntered.text;
  phoneNumbers = [[NSMutableArray alloc] initWithCapacity:3];
  [phoneNumbers addObject:self.homePhone.text];
  [phoneNumbers addObject:self.workPhone.text];
  [phoneNumbers addObject:self.cellPhone.text];

  // create dictionary with values in UITextFields
  NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: personName, phoneNumbers, nil] forKeys:[NSArray arrayWithObjects: @"Name", @"Phones", nil]];

  NSString *error = nil;
  // create NSData from dictionary
  NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

  // check is plistData exists
  if(plistData)
  {
    // write plistData to our Data.plist file
    [plistData writeToFile:plistPath atomically:YES];
  }
  else
  {
    NSLog(@"Error in saveData: %@", error);
  }
}

You should just go from dictionary to file. It will save it out as a plist.

NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: personName, phoneNumbers, nil] forKeys:[NSArray arrayWithObjects: @"Name", @"Phones", nil]];

NSLog(@"Dictionary is %@", plistDict);    
NSLog(@"Saving to %@", plistPath);

[plistDict writeToFile:plistPath atomically:YES];

I am assuming your plistPath is legit.

Your code is totally good. I tried the same code in my machine its working fine. If still you are facing the same issue then you can use below api and check for creating NSData from dictionary

+(NSData *)dataWithPropertyList:(id)plist format:(NSPropertyListFormat)format options:(NSPropertyListWriteOptions)opt error:(out NSError **)error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM