It’s commonplace that I have to obtain files with a particular extension from one folder. I don’t recall where but I found the script included below. With one exception it does what I want, but I wondered if there might be any improvements:
on getFiles(sourceFolder, fileExtensions) -- sourceFolder is POSIX path and fileExtensions is list of file extensions
set fileManager to current application's NSFileManager's defaultManager()
set theFolder to current application's |NSURL|'s fileURLWithPath:sourceFolder
set folderContents to fileManager's contentsOfDirectoryAtURL:theFolder includingPropertiesForKeys:{} options:(current application's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)
set theFiles to current application's NSPredicate's predicateWithFormat_("pathExtension.lowercaseString IN %@", fileExtensions)
set theFiles to folderContents's filteredArrayUsingPredicate:theFiles
return theFiles as list
end getFiles
I need the returned list to be sorted by name in ascending order. I added a sort routine to the script but received an unrecognized-selector error, presumably because I cannot sort URL’s in this manner. I looked at the NSArrray and NSURL documentation but didn’t find a solution. How can I fix this or is there a better way.
on getFiles(sourceFolder, fileExtensions) -- sourceFolder is POSIX path and fileExtensions is list of file extensions
set fileManager to current application's NSFileManager's defaultManager()
set theFolder to current application's |NSURL|'s fileURLWithPath:sourceFolder
set folderContents to fileManager's contentsOfDirectoryAtURL:theFolder includingPropertiesForKeys:{} options:(current application's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)
set theFiles to current application's NSPredicate's predicateWithFormat_("pathExtension.lowercaseString IN %@", fileExtensions)
set theFiles to folderContents's filteredArrayUsingPredicate:theFiles
set sortedFiles to (theFiles's sortedArrayUsingSelector:"compare:") -- error "-[NSURL compare:]: unrecognized selector sent to instance 0x600001825e00" number -10000
return sortedFiles as list
end getFiles
Thanks for the help.