如何只获取NSUrl数组的文件名

时间:2018-01-19 23:38:55

标签: ios objective-c arrays

我有一个NSUrl数组,但我只需要在tableview文本标签单元格中显示每个路径的文件名。

我从文档目录中获取文件并过滤了.csv文件,这些文件是我需要在表格视图的单元格中显示的文件。

这是我的代码:

        NSError *err;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSURL *documentDirectoryURL = [fileManager URLForDirectory:NSDocumentDirectory
                                                          inDomain:NSUserDomainMask
                                                 appropriateForURL:nil
                                                            create:false
                                                             error:&err];

        NSMutableArray *files = [[fileManager contentsOfDirectoryAtURL:documentDirectoryURL
                                            includingPropertiesForKeys:@[NSURLCreationDateKey ]
                                                               options:0
                                                                 error:&err] mutableCopy];

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension='.csv'"];
        NSArray *csvFiltered = [files filteredArrayUsingPredicate:predicate];

////////////


NSMutableArray*allItems = [NSMutableArray new];

  for (NSURL*paramURL in csvFiltered)
        {
            NSString *basenameOnly = documentDirectoryURL.lastPathComponent.stringByDeletingPathExtension;


           [allItems addObject:basenameOnly];
        }

        NSLog(@"%@", allItems);
        self.dirList = [allItems mutableCopy];

        self.data.reloadData;
    }


        BOOL ascending = YES;
        [files sortUsingComparator:^(NSURL *lURL, NSURL *rURL) {
            NSDate *lDate, *rDate;
            [lURL getResourceValue:&lDate forKey:NSURLCreationDateKey error:nil];
            [rURL getResourceValue:&rDate forKey:NSURLCreationDateKey error:nil];
            return ascending ? [lDate compare:rDate] : [rDate compare:lDate];
        }];

4 个答案:

答案 0 :(得分:0)

您可以使用它来排除数组中每个项目的.csv [4个字符]

NSMutableArray*allItems = [NSMutableArray new];

 for ( NSURL* paramURL in csvFiltered )
 {
     NSString*fullfileWithExten = [paramURL lastPathComponent];

     NSString*filename = [fullfileWithExten substringToIndex:[fullfileWithExten length]- 4];

     [allItems addObject:filename];
 }

答案 1 :(得分:0)

NSURLNSString都具有返回文件路径部分的属性。所以给定一个文件URL:

NSURL *itemURL = ...

没有扩展名的路径的最后一个组件只是由:

给出
NSString *basenameOnly = itemURL.lastPathComponent.stringByDeletingPathExtension;

其中NSURL' s lastPathComponent剥离任何只留下最终文件组件的目录,NSString' s stringByDeletingPathExtension然后剥离扩展

HTH

答案 2 :(得分:0)

首先,我有déjà vu

其次 只获取NSUrl数组的文件名。您将无法按创建日期对文件进行排序。

您无法使用谓词过滤NSURL数组,必须在循环中过滤文件。

要将过滤后的数组用作数据源,请先在.h文件中创建一个属性

@property NSMutableArray<NSURL *> *files; 

在.m文件中创建一个单独的方法来对文件进行排序

- (void)sortFilesByCreationDateAscending:(BOOL)ascending
{
    [self.files sortUsingComparator:^(NSURL *lURL, NSURL *rURL) {
        NSDate *lDate, *rDate;
        [lURL getResourceValue:&lDate forKey:NSURLCreationDateKey error:nil];
        [rURL getResourceValue:&rDate forKey:NSURLCreationDateKey error:nil];
        return ascending ? [lDate compare:rDate] : [rDate compare:lDate];
    }];
}

获取文件,过滤它们并在viewDidLoad中对它们进行排序。然后重新加载表视图

- (void)viewDidLoad {
    [super viewDidLoad]:
    self.files = [[NSMutableArray alloc] init];
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *documentDirectoryURL = [fileManager URLForDirectory:NSDocumentDirectory
                                                      inDomain:NSUserDomainMask
                                             appropriateForURL:nil
                                                        create:false
                                                         error:nil];

    NSArray<NSURL *> *fileURLs = [fileManager contentsOfDirectoryAtURL:documentDirectoryURL
                                                    includingPropertiesForKeys:@[NSURLCreationDateKey]
                                                                       options:0
                                                                         error:&error];
    if (error) { 
       NSLog(@"%@", error); 
       return; 
    }
    for (NSURL *anURL in fileURLs) {
        if ([anURL.pathExtension isEqualToString:@"csv"]) {
            [self.files addObject: anURL];
        }
    }
    [self sortFilesByCreationDateAscending:YES];
    [self.tableView reloadData];
}

numberOfRowsInSection返回self.files.count

cellForRowAtIndexPath中获取索引路径的URL并显示文件名

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *simpleTableIdentifier = @"SimpleTableItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath: indexPath];
    NSURL *url = self.files[indexPath.row];
    cell.textLabel.text = url.lastPathComponent;
    return cell;
}

要以另一个方向对文件进行排序,请使用适当的BOOL值调用sortFilesByCreationDateAscending并重新加载表格视图。

答案 3 :(得分:-1)

尝试以下代码

NSMutableArray *fileNamesArray = [[NSMutableArray alloc] init];
[fileNamesArray addObject:@"www.abc.com/path/movie1.mp4"];
[fileNamesArray addObject:@"www.abc.com/path/movie2.qt"];
[fileNamesArray addObject:@"www.abc.com/path/movie3.mov"];
[fileNamesArray addObject:@"www.abc.com/path/movie4.movv"];

NSLog(@"fileNamesArray===%@", fileNamesArray);

NSMutableArray *finalFileNamesArray = [[NSMutableArray alloc] init];
NSString *fileNameWithExtension;
NSString *fileNameWithWithoutExtension;
for (int i=0;i<fileNamesArray.count;i++) {
    fileNameWithExtension = [self fetchFileNameWithExtension:[fileNamesArray objectAtIndex:i]];
    fileNameWithWithoutExtension = [self fetchFileNameWithoutExtension:fileNameWithExtension];
    [finalFileNamesArray addObject:fileNameWithWithoutExtension];
}

NSLog(@"finalFileNamesArray===%@", finalFileNamesArray);

然后在viewDidLoad

之外添加
-(NSString *) fetchFileNameWithExtension:(NSString *) fullPath {
    NSArray *parts = [fullPath componentsSeparatedByString:@"/"];
    return [parts lastObject];
}

-(NSString *) fetchFileNameWithoutExtension:(NSString *) fullPath {
    NSArray *parts = [fullPath componentsSeparatedByString:@"."];
    return [parts firstObject];
}

输出如下

2018-01-20 12:08:25.459 Temp[3622:103513] fileNamesArray===(
    "www.abc.com/path/movie1.mp4",
    "www.abc.com/path/movie2.qt",
    "www.abc.com/path/movie3.mov",
    "www.abc.com/path/movie4.movv"
)
2018-01-20 12:08:25.459 Temp[3622:103513] finalFileNamesArray===(
    movie1,
    movie2,
    movie3,
    movie4
)

注意: 我可以在fetchFileNameWithoutExtension内混合fetchFileNameWithExtension,但我要分开以获得更明确的信息。