iOS 開發之 - Plist檔案的基本操作

來源:互聯網
上載者:User

標籤: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);    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.