5

在 iOS 5 中工作我已经从我的文档目录中读取了一个文件名列表,该数组称为“文件列表”。我正在尝试获取不带扩展名的文件名列表。只有我列表中的姓氏已删除扩展名。有任何想法吗?

- (IBAction)getFile:(id)sender
{  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory =[paths objectAtIndex:0];
    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSString *names = [[[fileList valueForKey:@"description"]componentsJoinedByString:@"\n"]stringByDeletingPathExtension];

    NSLog(@"File Name Is \n%@",names);    
    showFile.text = names; 
}
4

2 回答 2

10
- (IBAction)getFile:(id)sender
{  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory =[paths objectAtIndex:0];
    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSString *names = nil;
    for (NSString *name in fileList){
        if (!names) names = [[name lastPathComponent] stringByDeletingPathExtension];
        else names = [names stringByAppendingFormat:@" %@",[[name lastPathComponent] stringByDeletingPathExtension]];
    }
    NSLog(@"File Name Is \n%@",names
}
于 2012-07-21T22:04:21.547 回答
2

看起来您正在使用数组的描述来获取完整的数组内容,然后您正在删除整个文件的文件扩展名,而不是从每个单独的文件中删除。首先尝试删除文件扩展名:

NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:[fileList count]];
[fileList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [newArray addObject:[obj stringByDeletingPathExtension]];
}];
NSString *names = [newArray componentsJoinedByString:@"\n"];
showFile.text = names;

enumerateObjectsUsingBock方法遍历数组中的每个项目。在代码块中,您获取该对象,删除路径扩展名,并将其添加到新数组中。处理完完整数组后,您可以使用它们componentsJoinedByString在每个文件名之间添加换行符。

于 2012-07-21T22:13:24.683 回答