2012-04-01 6 views

答えて

1

NSArray *folders = [[NSFileManager defaultManager]contentsOfDirectoryAtURL:[self applicationDocumentsDirectory] includingPropertiesForKeys:[NSArray arrayWithObject:@"NSURLIsDirectoryKey"] options:0 error:nil]; 
if (folders) { 
    for (NSURL *url in folders) { 
     [[NSFileManager defaultManager]removeItemAtURL:url error:nil]; 
    } 
} 

をしかし、それはすべて削除され、フォルダだけでなく、このコードスニペットは、あるだけdirectioriesを削除します。

NSFileManager *fileManager = [[NSFileManager alloc] init]; 
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 

NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil]; 
for (NSString *file in files) { 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file]; 
    NSError *error; 
    if ([[fileManager contentsOfDirectoryAtPath:fullPath error:&error] count]==0) { 
     // check if number of files == 0 ==> empty directory 
     if (!error) { 
      // check if error set (fullPath is not a directory and we should leave it alone) 
      [fileManager removeItemAtPath:fullPath error:nil]; 
     } 
    } 
} 

あなたは、単にすべてのディレクトリを削除したい場合は(両方ない空)スニペットは、このように簡略化することができます。

NSFileManager *fileManager = [[NSFileManager alloc] init]; 
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 

NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil]; 
for (NSString *file in files) { 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file]; 
    if ([fileManager contentsOfDirectoryAtPath:fullPath error:nil]) 
     [fileManager removeItemAtPath:fullPath error:nil]; 
} 
関連する問題