如何获取存储在NSDocumentDirectory中的文件的名称?

时间:2012-08-15 18:33:56

标签: iphone ios filenames nsdocumentdirectory

我的NSDocumentsDirectory中保存了一些文件,如何获取这些文件的名称,然后在uitableview中显示这些名称?

我只想将对象的名称检索为NSString,我能够将文件检索为对象而不是它们的名称。

以下是代码:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSError * error;
objectsAtPathArray =  (NSMutableArray*)[[NSFileManager defaultManager]
                      contentsOfDirectoryAtPath:documentsDirectory error:&error];
[objectsAtPathArray removeObjectAtIndex:0];

最后一行是删除.DS_Store文件

3 个答案:

答案 0 :(得分:2)

试试这个,

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

    objectsAtPathArray = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil]mutableCopy];

    for(int i = 0; i < [objectsAtPathArray count]; i++)
    {
       if (![[objectsAtPathArray objectAtIndex:i]isEqualToString:@".DS_Store"])
       {
         [NewArray addObject:[objectsAtPathArray objectAtIndex:i]];
          NSLog(@"NewArray=%@",[NewArray objectAtIndex:i]);
       }
     }

答案 1 :(得分:0)

添加一个(for in)循环为我做了诀窍,

for (NSString *fileName in self.objectsAtPathArray){

   cell.textLabel.text = fileName;
} 

答案 2 :(得分:0)

这将是正确的:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *imageFilenames = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];

for (int i = 0; i < [imageFilenames count]; i++)
    {

    NSString *imageName = [NSString stringWithFormat:@"%@/%@",documentsDirectory,[imageFilenames objectAtIndex:i] ];

        if (![[imageFilenames objectAtIndex:i]isEqualToString:@".DS_Store"])
        {
          UIImage *myimage = [UIImage imageWithContentsOfFile:imageName];
          UIImageView *imageView = [[UIImageView alloc] initWithImage:_myimage];
        }
    }