重要概念:某些路徑下“只能讀,不能寫”的原因
iPhone、ipad真機上
Resouces文件夾:是只讀的,無法寫入。
document 和temp文件夾:可讀,可寫。
一、工程結構
二、源代碼
1、頭文件:PlistManage.h
@interface PlistManage : NSObject -(void)resourcePathFileRead;//當前工程資源目錄,不同於真機“沙箱”中的路徑 -(NSString *)docPath;//獲取document文件夾路徑 -(BOOL)isDirNeedCreate:(NSString *)dirPath;//判斷目錄是否需要新創建 -(BOOL)isFileNeedCreate:(NSString *)filePath;//判斷文件是否需要創建 -(void) doAdd; -(void) doRead; -(void) doModify; -(void) doDelete; @end
2、一些基本函數的實現:
//獲取document目錄路徑 -(NSString *)docPath { NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); return [paths objectAtIndex:0]; } //路徑是否需要創建 -(BOOL)isDirNeedCreate:(NSString *)dirPath { if ( NO == [[NSFileManager defaultManager] fileExistsAtPath:dirPath] ) { return [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:NULL]; } return NO; } //文件是否需要創建 -(BOOL)isFileNeedCreate:(NSString *)filePath{ if ( NO == [[NSFileManager defaultManager] fileExistsAtPath:filePath] ) { return [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]; } return NO; }
3、添加:包括創建不存在的空文件
-(void) doAdd{ NSString *docPath=[self docPath]; NSLog(@"當前docment路徑:\n%@",docPath); NSString *dataFile=[docPath stringByAppendingPathComponent:@"docData.plist"]; if (YES==[self isFileNeedCreate:dataFile]) { NSLog(@"文件原先不存在,現已新建空文件!"); }else{ NSLog(@"文件已存在,無需創建!"); } NSMutableDictionary *plistDic = [[NSMutableDictionary alloc ] init]; // 添加2個“單條記錄” [plistDic setObject:@"shanghai" forKey:@"recordKey001"]; [plistDic setObject:@"beijing" forKey:@"recordKey002"]; // 添加2個“字典記錄” [plistDic setObject:[NSDictionary dictionaryWithObjectsAndKeys:@"Jack",@"name",@"22",@"age",nil] forKey:@"dicKey001"]; [plistDic setObject:[NSDictionary dictionaryWithObjectsAndKeys:@"Tom",@"name",@"33",@"age",nil] forKey:@"dicKey002"]; [plistDic writeToFile:dataFile atomically:YES];//完全覆蓋 NSLog(@"添加內容完成!!"); }
運行結果:
對應路徑下生成了新文件:
內容如下:
4、讀取
-(void) doRead{ NSString *dataFile=[[self docPath] stringByAppendingPathComponent:@"docData.plist"]; //讀取所有內容 NSDictionary* dic = [NSDictionary dictionaryWithContentsOfFile:dataFile]; NSLog(@"完整內容:\n%@",dic); //讀取第一層“字典記錄” NSDictionary* dicValue=[dic objectForKey:@"dicKey001"]; NSLog(@"讀取第一層“字典記錄”:\n%@",dicValue); //讀取第一層“字典記錄”中的“子元素” NSLog(@"讀取第一層“字典記錄”中的“子元素”:\nname=%@",[dicValue objectForKey:@"name" ]); //讀取第一層“單條記錄” NSLog(@"讀取第一層“單條記錄”:\nrecordKey001=%@",[dic objectForKey:@"recordKey001"]); }
運行結果: