开发者

How to fill an NSArray with directory names?

I'm looking for a way to fill an NSArray with NSStrings that are the names of the directories in the apps documents directory.

This is what I have so far:

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

    for (//loop until no more directories)
    {
         NSString *newDir = [documentsDirectory stringByAppendingPathComponent:path];

         //Code for retrieving directory names
         [directoriesArray addObject:newDir]; 
    }

I开发者_StackOverflow'm not sure what the for loop's conditions need to be and I'm not sure how to retrieve the directories names.

Thanks for the advice in advance.


Try this

NSFileManager *fileManager = [NSFileManager defaultManager];
filesArray = [[fileManager contentsOfDirectoryAtPath:urDocumentsFolderPath error:nil] retain];

for(NSString *file in filesArray) {
//Do something
}

So in your case

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
filesArray = [[fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil] retain];
for(NSString *file in filesArray) 
{
  NSString *newDir = [documentsDirectory stringByAppendingPathComponent:file];
  //Code for retrieving directory names
  [directoriesArray addObject:newDir]; 
}

Hope this helps


"apps documents directory" = ~/Users/User/Applications? NSDocumentsDirectory or NSApplicationDirectory?

Maybe:

NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL fileIsDirectory = FALSE;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *content = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL]; //OSX v10.5
NSEnumerator *enumeratorContent = [content objectEnumerator];
NSString *file;

while ((file = [emumeratorContent nextObject])) {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    if (fileManager fileExistAtPath:[documentsDirectory stringByAppendingPathComponent:file] isDirectory:&fileIsDirectory && fileIsDirectory)
        [directoriesArray addObject:file];
    [pool drain];

Try to use NSDirectoryEnumerator(OSX v.10.0) or NSURL too (OSX v.10.6).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜