iOS Plist文件操做之寫入/讀取/刪除

  • 寫入數據到plist文件atom

  •   //獲取路徑對象
        NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [pathArray objectAtIndex:0];
        //獲取文件的完整路徑
        NSString *filePatch = [path stringByAppendingPathComponent:@"xiaoxi.plist"];
        
        //上面3句能夠寫成這一句
    //    NSString *filePatch = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"xiaoxi.plist"];
        
    //    NSLog(@"------filepath---%@",filePatch);
        /*
         *
         下面是個人plist路徑,在桌面空白處點擊一下,前往-按住option-資源庫-Developer-CoreSimulator-Devices......就按照下面路徑找到plist所在的位置
         *
        /Users/baiteng01/Library/Developer/CoreSimulator/Devices/92444384-5241-4934-B078-1A7241F1B687/data/Containers/Data/Application/73005382-D1FB-4BC2-BB4E-1FBC64284141/Documents/xiaoxi.plist
         *
         */
        
        //寫入數據到plist文件
        NSMutableDictionary *dic1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"小小虎",@"name",@"5",@"age",@"boy",@"sex",nil];
        
        NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"小小兮",@"name",@"6",@"age",@"girl",@"sex",nil];
        
        //將上面2個小字典保存到大字典裏面
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setObject:dic1 forKey:@"一年級"];
        [dataDic setObject:dic2 forKey:@"二年級"];
        //寫入plist裏面
        [dataDic writeToFile:filePatch atomically:YES];
        
        //讀取plist文件的內容
        NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:filePatch];
        NSLog(@"---plist一開始保存時候的內容---%@",dataDictionary);
  • 對plist文件內容進行/刪除/修改/添加/寫入操做code

  •  //修改字典裏面的內容,先按照結構取到你想修改內容的小字典
        NSMutableDictionary *dd = [dataDictionary objectForKey:@"一年級"];
        [dd setObject:@"我更名字了哦" forKey:@"name"];
        [dd setObject:@"我添加的新內容" forKey:@"content"];
        [dd removeObjectForKey:@"age"];
        
        //修改爲功之後,將這個小字典從新添加到大字典裏面
        [dataDictionary setObject:dd forKey:@"一年級"];
        
        [dataDictionary writeToFile:filePatch atomically:YES];
        NSLog(@"---plist作過操做以後的字典裏面內容---%@",dataDictionary);
  • 刪除plist文件對象

  •     //清除plist文件,能夠根據我上面講的方式進去本地查看plist文件是否被清除
        NSFileManager *fileMger = [NSFileManager defaultManager];
        
        NSString *xiaoXiPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"xiaoxi.plist"];
        
        //若是文件路徑存在的話
        BOOL bRet = [fileMger fileExistsAtPath:xiaoXiPath];
        
        if (bRet) {
            
            NSError *err;
            
            [fileMger removeItemAtPath:xiaoXiPath error:&err];
        }
相關文章
相關標籤/搜索