How to remove a directory and its contents using NSFileManager
New to Objective C. I have created a few directories which contain pdf files for an iPhone app. How can I delete a directory and its contents using NSFileManager?
Do 开发者_StackOverflowI need to loop through and remove the contents first? Any code samples would be much appreciated.
Thanks in advance.
To start off, it would be wise to look through Apple's NSFileManager
documentation for the iPhone: NSFileManager Class Reference. Second, look at NSFileManager
's -removeItemAtPath:error:
method and its documentation. That's what you're looking for.
Heres some code I use that Ive edited to suit the question
- (NSMutableString*)getUserDocumentDir {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSMutableString *path = [NSMutableString stringWithString:[paths objectAtIndex:0]];
return path;
}
- (BOOL) createMyDocsDirectory
{
NSMutableString *path = [self getUserDocumentDir];
[path appendString:@"/MyDocs"];
NSLog(@"createpath:%@",path);
return [[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:NO
attributes:nil
error:NULL];
}
- (BOOL) deleteMyDocsDirectory
{
NSMutableString *path = [self getUserDocumentDir];
[path appendString:@"/MyDocs"];
return [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
You can get document directory by using this:
NSString *directoryPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/"];
** Remove full directory path by using this:
BOOL success = [fileManager removeItemAtPath:directoryPath error:nil];
if (!success) {
NSLog(@"Directory delete failed");
}
** Remove the contents of that directory using this:
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:directoryPath]) {
NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:directoryPath];
NSString *documentsName;
while (documentsName = [dirEnum nextObject]) {
NSString *filePath = [directoryPath stringByAppendingString:documentsName];
BOOL isFileDeleted = [fileManager removeItemAtPath:filePath error:nil];
if(isFileDeleted == NO) {
NSLog(@"All Contents not removed");
break;
}
}
NSLog(@"All Contents Removed");
}
** You can edit directoryPath
as per your requirement.
精彩评论