简体   繁体   English

如何从iOS 5的NSArray中的文件列表中删除文件扩展名

[英]How do I remove the file extension from a list of files in an NSArray in iOS 5

Working in iOS 5 I have read a list of file names from my documents directory the array is called "file list". 在iOS 5中工作时,我已经从文档目录中读取了文件名列表,该数组称为“文件列表”。 I am trying to get a list of file names without extensions. 我正在尝试获取不带扩展名的文件名列表。 Only the last name in my list has the extension removed. 仅列表中的姓氏已删除扩展名。 Any ideas? 有任何想法吗?

- (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; 
}
- (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
}

Looks like you are using the description of the array to get the full array contents, and then you are removing the file extension for the whole thing rather than from each individual file. 看起来您正在使用数组的描述来获取完整的数组内容,然后正在删除整个文件的扩展名,而不是从每个单独的文件中删除。 Try removing the filename extensions first: 尝试先删除文件扩展名:

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;

The enumerateObjectsUsingBock method goes through each item in the array. enumerateObjectsUsingBock方法遍历数组中的每个项目。 In the code block you take that object, delete the path extension, and add it to a new array. 在代码块中,获取该对象,删除路径扩展,然后将其添加到新数组中。 After the full array has been processed, you can them use componentsJoinedByString to add the newline between each filename. 在处理完整个数组之后,您可以使它们使用componentsJoinedByString在每个文件名之间添加换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM