0

I am using NSDirectoryEnmerator to find all file with a suffix of png and jpg with following code:

NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:containerURL includingPropertiesForKeys:[NSArray array] options:0 errorHandler:^BOOL(NSURL *url, NSError *error) {
    // handle error
    return NO;
}];

NSString *fileOrDirectory = nil;
while ((fileOrDirectory = [directoryEnumerator nextObject])) {
    if([fileOrDirectory hasSuffix:@".jpg"] || [fileOrDirectory hasSuffix:@".png"]){
        NSLog(@" find a image file %@", fileOrDirectory );
    }

}

But there is an error said that NSURL don't have a method hasSuffix

enter image description here

What happened and how to make this work? what does the type of the iterated elements exactly? the above code was frequently suggested by posts and was presumed to be a NSString but it can't work

armnotstrong
  • 8,605
  • 16
  • 65
  • 130
  • According to the error: `[directoryEnumerator nextObject]` returns apparently a `NSURL` object, not a `NSString` object. Replace maybe `fileOrDirectory = [directoryEnumerator nextObject]` with `fileOrDirectory = [directoryEnumerator nextObject].absoluteString`? The diff from the linked answer is `enumeratorAtURL:` vs `enumartorAtPath:` I guess, which explains the different. – Larme Sep 06 '17 at 09:21
  • @Larme I have found plenty of [code snippet](https://eezytutorials.com/ios/nsdirectoryenumerator-by-example.php#.Wa-0jtMjHBI) on the internet that using a `NSString`, are they all wrong and misleading? – armnotstrong Sep 06 '17 at 09:23
  • Sorry, I edited my previous comment: "The diff from the linked answer is enumeratorAtURL: vs enumartorAtPath: I guess, which explains the different class of object returned" – Larme Sep 06 '17 at 09:24

1 Answers1

1

The enumeratorAtURL method works with NSURL objects rather than strings (which the exception reason clearly reveals), you can simply compare the pathExtension:

if ([fileOrDirectory.pathExtension isEqualToString:@"jpg"] || 
    [fileOrDirectory.pathExtension isEqualToString:@"png"]) { ...
vadian
  • 274,689
  • 30
  • 353
  • 361