Re: NSFileManager and directories
Re: NSFileManager and directories
- Subject: Re: NSFileManager and directories
- From: Shaun Wexler <email@hidden>
- Date: Thu, 4 Sep 2003 02:21:15 -0700
On Sep 4, 2003, at 12:25 AM, Francisco Tolmasky wrote:
>
Is saying something like
>
NSArray *contents;
>
if(contents= [[NSFileManager defaultManager] directoryContentsAtPath:
>
aPath])
>
//do directory stuff
>
else
>
//do file stuff
>
>
a safe way to tell if the object at "aPath" is a directory or not?
There is a NSFileManager method called -fileExistsAtPath:isDirectory:
which will give you the answer.
I have a nice little method I wrote as a category on NSFileManager,
which returns a BOOL indicating whether there is a valid directory
structure with write permissions at the specified path, and (this is
the good part) it also attempts to create the directory hierarchy if it
doesn't exist. This method is really useful, and probably should be
added to Foundation by Apple... ;-)
--
Shaun Wexler
MacFOH
http://www.macfoh.com
@interface NSFileManager (SKWSupportExtensions)
- (BOOL)assertHierarchyForDirectoryPath:(NSString *)directory;
@end
@implementation NSFileManager (SKWSupportExtensions)
- (BOOL)assertHierarchyForDirectoryPath:(NSString *)directoryPath
{
BOOL isDirectory = NO;
BOOL doesExist = [self fileExistsAtPath:directoryPath
isDirectory:&isDirectory];
if (doesExist) {
return isDirectory ? [self isWritableFileAtPath:directoryPath] : NO;
} else {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *pathComponents = [[directoryPath stringByStandardizingPath]
pathComponents];
int index, count = index = [pathComponents count];
if (--index) {
do {
directoryPath = [directoryPath stringByDeletingLastPathComponent];
doesExist = [self fileExistsAtPath:directoryPath
isDirectory:&isDirectory];
} while (!doesExist && --index);
doesExist = doesExist && isDirectory && [self
isWritableFileAtPath:directoryPath];
if (doesExist) {
NSDictionary *enclosingFolderAttributes = [self
fileAttributesAtPath:directoryPath traverseLink:YES];
do {
directoryPath = [directoryPath
stringByAppendingPathComponent:[pathComponents objectAtIndex:index++]];
doesExist = [self createDirectoryAtPath:directoryPath
attributes:enclosingFolderAttributes];
} while (doesExist && index < count);
}
}
[pool release];
return doesExist;
}
}
@end
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.