2011-05-09 165 views
1

我有一個/ Documents/Images文件夾,在該文件夾中有幾個以年名命名的其他文件夾,在這些文件夾中我有圖像。我想刪除圖像文件夾中的所有內容(包括文件夾和這些文件夾中的圖像)。從某個文件夾中刪除所有文件和文件夾

我試了幾個代碼片段,但沒有刪除這些文件夾

我的方法:

- (void) clearCache:(NSString *) folderName{ 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectoryPath = [paths objectAtIndex:0]; 
NSFileManager *fm = [NSFileManager defaultManager]; 
NSString *directory = [documentsDirectoryPath stringByAppendingPathComponent:folderName]; 
NSLog(@"Removing items at path: %@",directory); 
    NSError *error = nil; 
BOOL succes = [fm removeItemAtPath:directory error:&error]; 

/*for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) { 
    //BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error]; 
    BOOL success = [fm removeItemAtPath:[directory stringByAppendingPathComponent:file] error:&error]; 
    if (!success || error) { 
     // it failed. 
    } 
}*/ 

}

+0

可能重複[如何在應用程序指定的目錄中刪除所有檔案?(http://stackoverflow.com/questions/2226600/how-to-delete-all-files-in -a-specified-directory-on-the-app) – Leena 2014-08-31 10:53:42

回答

8
NSFileManager *fm = [NSFileManager defaultManager]; 
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"urDirectory/"]; 
NSError *error = nil; 
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) { 
    BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error]; 
    if (!success || error) { 
     // it failed. 
    } 
} 

希望這有助於

+1

你打算把'documentsDirectory'設置爲'NSDocumentDirectory'嗎? – 2014-05-06 02:49:49

相關問題