对Plist文件进行读写
2010-09-07 17:09 Tracy E 阅读(1010) 评论(0) 编辑 收藏 举报读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];
}