The docs for NSWorkspace.shared.icon(forFileType:
state:
/*
* Get the icon for a given file type.
*
* The file type may be a filename extension, or a HFS code encoded via NSFileTypeForHFSTypeCode, or a Universal Type Identifier (UTI).
*
* Returns a default icon if the operation fails.
*
*/
// Swift
open func icon(forFileType fileType: String) -> NSImage
// Objective-C
- (NSImage *)iconForFileType:(NSString *)fileType;
Note:
Returns a default icon if the operation fails.
How can you tell if the operation has "failed" and a default icon is being returned?
Is there a way to determine if you're getting a default icon back without doing an expensive Image or Data comparison?
After a quick test, it looks like when iconForFileType
fails, it returns the same pointer every time. That makes sense, because it probably just interns a single, shared reference to that "no file type" image.
So, you could grab that pointer once, with a known-unknown file type:
// Do this once, at program startup for example, and keep the reference
NSImage* x = [[NSWorkspace sharedWorkspace] iconForFileType:@".this_is_not_a_file_type"];
Then just do a pointer comparison:
NSImage* y = [[NSWorkspace sharedWorkspace] iconForFileType:@".xxx"];
NSLog(@"%p %p", x, y);
if (x == y)
// `iconForFileType` failed