保存然后从iOS中的文档目录中删除文件

时间:2014-05-22 22:19:48

标签: ios ipad sandbox

我能够保存和删除iOS文档目录中的文件,但是,我遇到了一个错误,我从那里删除后无法保存新文件。有人可以解释为什么这样做吗?

- (IBAction)saveInfo:(id)sender {

//int x = 0;
//if (x == 0) { // for testing without field checking
if([self checkFields]){

NSString *resultLine;
// save all data to string using csv formatting
    if (isClassProject) {
        //NSString *waypointText = self.Waypoints.text;
        resultLine=[NSString stringWithFormat:@"Name,Partner,Temperature,Weather,Project,Instructor/Mentor,Class,Waypoints/Trackers,Notes\n%@,%@,%@,%@,%@,%@,%@,%@,%@\n",
                    [[self YourName] text], [[self PartnersName] text], [[self CurrentTemp] text],
                    [[self CurrentWeather] text], [[self ProjectName] text], [[self InstructorName] text],
                    [[self ClassNum] text], [[self Waypoints] text], [[self Notes] text]];
        //NSLog(@"%@",[[self YourName] text]);
        NSLog(@"%@",resultLine);
    }
    else{
        resultLine=[NSString stringWithFormat:@"Name,Partner,Temperature,Weather,Project,Instructor/Mentor,Waypoints/Trackers,Notes\n%@,%@,%@,%@,%@,%@,%@,%@\n",
                    [[self YourName] text], [[self PartnersName] text], [[self CurrentTemp] text],
                    [[self CurrentWeather] text], [[self ProjectName] text], [[self InstructorName] text],
                    [[self Waypoints] text], [[self Notes] text]];
        NSLog(@"%@",resultLine);
    }

    NSArray *paths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // get today's date for file name
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

    NSString *todayDate = [dateFormatter stringFromDate:today];

    //make a file name to write the data to using the documents directory:
    NSString *fileName = [NSString stringWithFormat:@"%@/%@_%@_%@.csv",documentsDirectory,
                          todayDate,[[self ProjectName] text],[[self YourName] text]];
    //create content - four lines of text
    //NSString *content = @"One\nTwo\nThree\nFour\nFive";
    //save content to the documents directory
    [resultLine writeToFile:fileName
              atomically:NO
                encoding:NSUTF8StringEncoding
                   error:nil];

    // now empty fields
    /*
    self.YourName.text =@"";
    self.PartnersName.text =@"";
    self.CurrentTemp.text =@"";
    self.CurrentWeather.text =@"";
    self.ProjectName.text =@"";
    self.InstructorName.text =@"";
    self.ClassNum.text =@"";
    self.Waypoints.text =@"";
    self.Notes.text =@"";*/
    //NSLog(@"Data Saved"); //for Xcode command line

}

- (IBAction)deleteAllFiles:(id)sender {
// set path to documents dir
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// if files exist then delete
 if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory]) {
    NSFileManager *manager = [NSFileManager defaultManager];
     NSLog(@"Found Files in documentsDirectory");
     NSError *error = nil;
     [manager removeItemAtPath:documentsDirectory error:&error];

    if (error){
        NSLog(@"There is an Error: %@", error);
    } else{
        NSLog(@"No files");
    }
}

3 个答案:

答案 0 :(得分:1)

我最终用以下代码解决了它:

- (IBAction)deleteAllFiles:(id)sender {

NSString *csvFile = @"csv";
NSString *jpgFile = @"jpg";
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];
// if files exist then delete
NSArray *contents = [[NSFileManager defaultManager]
                     contentsOfDirectoryAtPath: documentsDirectory error:&error];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;

while ((filename = [e nextObject])) {

    if ([[filename pathExtension] isEqualToString:csvFile]) {
        [fileManager removeItemAtPath:[documentsDirectory     stringByAppendingPathComponent:filename] error:NULL];
    }
    if ([[filename pathExtension] isEqualToString:jpgFile]) {
        [fileManager removeItemAtPath:[documentsDirectory     stringByAppendingPathComponent:filename] error:NULL];
    }
}

}

我在stackoverflow上找到了另一个允许你使用文件扩展名的例子。这对我来说非常合适,因为我只将jpg和csv文件保存到沙盒中。

答案 1 :(得分:0)

调用delete方法后无法将新文件保存到该目录的原因是该目录不再存在。

只需删除该目录的内容,而不是删除整个Documents目录。

例如:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: documentsDirectory error:&error]
if (error) {
     // Handle error
}
else {
    for (NSString *filename in ) {
        if (![[NSFileManager defaultManager] removeItemAtPath:filename error:&error];
            // Handle error
       }
    }
}

答案 2 :(得分:0)

Is there a way to delete them all at once?

您可以像以前一样删除。这意味着删除Document文件夹及其文件。

但是当您创建新文件时,您必须检查Document文件夹是否存在。如果没有,请创建文档文件夹:

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
if(![fm fileExistsAtPath:documentsDirectory]){
  // if Document folder is not existed, create it. 
  [ createFileAtPath:documentsDirectory contents:nil attributes:nil];
}
.... // do with your files