天天看點

iOS擷取沙盒路徑并寫入檔案

.h檔案中
//你需要的資料集合形式
@property(nonatomic,strong)NSMutableArray *groupArray;//數組
@property(nonatomic,strong)NSMutableDictionary *allDict;//字典

//判斷沙盒裡面是否有需要的對象
+(ShareDataHandleModel*)shareDataHandleModel;


//擷取沙盒檔案中document路徑
+(NSString*)documentPath;


//通過檔案名從沙盒讀資料
-(void)readDataFromDocumentWithFileName:(NSString*)fileName;//數組

-(void)readDataFromDocumentWithFileNameToDict:(NSString *)fileName;//字典


//寫入
-(void)myWirteTofile:(NSString*)fileName; 
 
.m檔案中
+(ShareDataHandleModel*)shareDataHandleModel
{
   //如果為空 建立一個新的
    if (nil==shareModel) {
                shareModel=[[ShareDataHandleModel alloc]init];
    }
    return shareModel;
}


//擷取沙盒檔案中document路徑
+(NSString*)documentPath
{
    NSArray *pathArray=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return pathArray[0];
}


//通過檔案名從沙盒讀資料(數組)
-(void)readDataFromDocumentWithFileName:(NSString*)fileName
{
    //拼接檔案路徑
    NSString *filePath=[[[self class]documentPath]stringByAppendingFormat:@"/%@",fileName];
    
    NSArray *tempArray=[NSArray arrayWithContentsOfFile:filePath];
    
    self.groupArray=[NSMutableArray arrayWithObject:tempArray];


}

//通過檔案名從沙盒讀資料(字典)
-(void)readDataFromDocumentWithFileNameToDict:(NSString *)fileName
{
    //拼接檔案路徑
    // NSString *filePath=[[[self class]documentPath]stringByAppendingFormat:@"/%@",fileName];
    
    NSString *filePath=[self appendPath:fileName];//使用下面封裝好的
    self.allDict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];
}


 

//封裝
-(NSString*)appendPath:(NSString*)fileName
{

    //拼接檔案路徑
    return [[[self class]documentPath]stringByAppendingFormat:@"/%@",fileName];

}


//寫入
-(void)myWirteTofile:(NSString*)fileName
{
    NSString *filePath=[self appendPath:fileName];
    
    NSMutableArray *a=self.groupArray[0];
    [a writeToFile:filePath atomically:YES];
    

}