网页浏览总次数

2011年4月20日星期三

转----iPhone 对Plist文件进行读写

读Plist文件
  NSString *errorDesc = nil;
  NSPropertyListFormat format;
  NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  NSString *plistPath = [rootPath stringByAppendingPathComponent:@"bookmarks.plist"];
  if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
  plistPath = [[NSBundle mainBundle] pathForResource:@"bookmarks" ofType:@"plist"];
  }
  NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
  context.bookmarksDic = (NSMutableDictionary *)[[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves
  format:&format
  errorDescription:&errorDesc] retain];
  keysArr = [[[context.bookmarksDic allKeys] sortedArrayUsingSelector:@selector(compare:)] retain];
  if (!context.bookmarksDic) {
  NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
  }
  写入Plist
  Context *context = [Context getInstance];
  NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
  NSUserDomainMask, YES) objectAtIndex:0];
  NSString *plistPath = [rootPath stringByAppendingPathComponent:@"bookmarks.plist"];
  NSString *error;
  NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:context.bookmarksDic
  format:NSPropertyListXMLFormat_v1_0
  errorDescription:&error];
  if(plistData) {
  [plistData writeToFile:plistPath atomically:YES];
  }
  else {
  NSLog(@"%@",error);
  [error release];
  }

没有评论:

发表评论