標籤:style blog http color os io strong 檔案
plist檔案是一個輕量級的資料庫,用於存放一些比較小的資料。下面是對plist的基本操作。
建立一個Plist檔案
我這裡是建立的一個以整體為Array,item是字典的plist檔案。
一般開發中,如果是要操作plist檔案的話。都是要把plist檔案放到沙箱(Document) 目錄下的
先得到資來源目錄:
//得到資來源目錄(建立的plist檔案)- (NSString *)getDataSourcePath:(NSString *) sourceName andType:(NSString *) fileType{ NSString *path = [[NSBundle mainBundle] pathForResource:sourceName ofType:fileType]; return path;}
得到沙箱 (Document)
//得到documents目錄- (NSString *)getDocumentPath:(NSString *) fileName{ //兩種擷取document路徑的方式 // NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documents = [paths objectAtIndex:0]; NSString *path = [documents stringByAppendingPathComponent:fileName]; return path;}
重點:
//得到沙箱plist檔案
NSString *documentPath = [self getDocumentPath:@"szPlistDemo.plist"];
//向該Document目錄添加資料 1 : 直接寫的方式, 2 : 將資源檔 複製到 documents目錄下
第一種方法:
// NSError *error;// if ([plistPath writeToFile:documentPath atomically:YES encoding:NSUTF8StringEncoding error:&error]) {// NSLog(@"file write success . ");// }else{// NSLog(@"error = %@",error);// }
第二種:
// 2 :複製到 documents目錄下 NSFileManager *manager = [NSFileManager defaultManager]; NSError *error; if ([manager fileExistsAtPath:documentPath]) { NSLog(@"file is exists"); }else{ if ([manager copyItemAtPath:plistPath toPath:documentPath error:&error]) { NSLog(@"file is not exists, copy success!"); }else{ NSLog(@"error = %@",error); return; } }
//像plist中寫入資料
//得到資來源目錄的資料
NSMutableArray *documentData = [[NSMutableArray alloc] initWithContentsOfFile:documentPath]; NSLog(@"documentData = %@",documentData); NSDictionary *dic = @{@"age":@"25",@"phone_num":@"1328820394"}; [documentData addObject:dic];
//寫入檔案
[documentData writeToFile:documentPath atomically:YES];
//刪除plist檔案
這裡我用了一個按鈕,點擊按鈕刪除plist檔案
NSError *error; NSFileManager *fileManager = [NSFileManager defaultManager]; if ([fileManager removeItemAtPath:documentPath error:&error]) { NSLog(@"remove success!"); }else{ NSLog(@"error = %@",error); }