1. 程式人生 > >ios 對plist檔案的修改

ios 對plist檔案的修改

這篇文章是自己通過實踐獲取,在網上查過很多資料,也走了不上的彎路,由於剛開始學子不久,只是把自己遇到的問題貢獻給大家

一,建立檔案

    //獲取路徑物件

NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

//獲取完整路徑

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *plistPath = [documentsDirectory stringByAppendingPathComponent

:@"test.plist"];

NSMutableDictionary *dictplist = [[NSMutableDictionaryalloc ] init];

//設定屬性值

    [dictplist setObject:@"張三" forKey:@"name"];

    [dictplist setObject:@"李四"forKey:@"name1"];

    [dictplist setObject:@"王五"forKey:@"name2"];

//寫入檔案

    [dictplist writeToFile:plistPath atomically:YES];

這個是建立了一個簡單的plist

檔案,建立後的圖1為:


下面是建立了一種多鍵值的plist檔案,程式碼和圖如下:

//獲取路徑物件

NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);  

//獲取完整路徑

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"test.plist"

];

NSMutableDictionary *dictplist = [[NSMutableDictionaryalloc ] init];

//定義第一個外掛的屬性

NSMutableDictionary *plugin1 = [[NSMutableDictionaryalloc]init];

    [plugin1 setObject:@"張三"forKey:@"name1"];

    [plugin1 setObject:@"李四"forKey:@"name2"];

//定義第二個外掛的屬性

NSMutableDictionary *plugin2 = [[NSMutableDictionaryalloc]init];

    [plugin2 setObject:@"王五"forKey:@"name1"];

    [plugin2 setObject:@"趙斌"forKey:@"name2"];

//設定屬性值

    [dictplist setObject:plugin1 forKey:@"初一班"];

    [dictplist setObject:plugin2 forKey:@"初二班"];

//寫入檔案

    [dictplist writeToFile:plistPath atomically:YES];

圖2:

    

針對圖1進行修改的程式,程式碼如下:

    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)       objectAtIndex:0]stringByAppendingPathComponent:@"test.plist"];    

NSMutableDictionary *applist = [[[NSMutableDictionaryalloc]initWithContentsOfFile:path]mutableCopy];    

    NSString *name = [applist objectForKey:@"name"];    

    name = @"山山";   

    [applist setObject:name forKey:@"name"];

    [applist writeToFile:path atomically:YES];

執行後如下圖:

    

針對圖2進行修改的程式,程式碼如下:

      [dictplist writeToFile:plistPath atomically:YES];

NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"test.plist"];

//根據路徑獲取test.plist的全部內容

NSMutableDictionary *infolist= [[[NSMutableDictionaryalloc]initWithContentsOfFile:path]mutableCopy];

//獲取初一班的資訊

    NSMutableDictionary *info = [infolist objectForKey:@"初一班"];

    NSString *name1 = [info objectForKey:@"name1"];

    name1 = @"山山";

    [info setValue:name1 forKey:@"name1"];

    [infolist setValue:info forKey:@"初一班"];

    [infolist writeToFile:path atomically:YES];

圖如下:

    

以上兩個修改資訊的地方,必須要加入紅色標記的方法,才能在表裡進行增改操作。

以上是個人的學習心得,請大家多多指教。