NSWorkspace `icon(forFileType:` 返回默认图标
NSWorkspace `icon(forFileType:` returning default icon
NSWorkspace.shared.icon(forFileType:
状态的文档:
/*
* 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;
注:
Returns a default icon if the operation fails.
如何判断该操作是否有 "failed" 并且正在返回默认图标?
有没有一种方法可以确定您是否正在恢复默认图标而无需 进行昂贵的图像或数据比较?
经过快速测试,看起来 iconForFileType
失败时,它每次都 returns 相同的指针。这是有道理的,因为它可能只是实习了对该 "no 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"];
然后做一个指针比较:
NSImage* y = [[NSWorkspace sharedWorkspace] iconForFileType:@".xxx"];
NSLog(@"%p %p", x, y);
if (x == y)
// `iconForFileType` failed
NSWorkspace 扩展改为 return nil
如果 icon(forFileType:
操作失败:
extension NSWorkspace {
func iconOptional(forFileType fileType: String) -> NSImage? {
let icon = self.icon(forFileType: fileType)
let iconDefault = self.icon(forFileType: "") // "Returns a default icon if the operation fails."
return icon === iconDefault ? nil : icon
}
}
NSWorkspace.shared.icon(forFileType:
状态的文档:
/*
* 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;
注:
Returns a default icon if the operation fails.
如何判断该操作是否有 "failed" 并且正在返回默认图标?
有没有一种方法可以确定您是否正在恢复默认图标而无需 进行昂贵的图像或数据比较?
经过快速测试,看起来 iconForFileType
失败时,它每次都 returns 相同的指针。这是有道理的,因为它可能只是实习了对该 "no 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"];
然后做一个指针比较:
NSImage* y = [[NSWorkspace sharedWorkspace] iconForFileType:@".xxx"];
NSLog(@"%p %p", x, y);
if (x == y)
// `iconForFileType` failed
NSWorkspace 扩展改为 return nil
如果 icon(forFileType:
操作失败:
extension NSWorkspace {
func iconOptional(forFileType fileType: String) -> NSImage? {
let icon = self.icon(forFileType: fileType)
let iconDefault = self.icon(forFileType: "") // "Returns a default icon if the operation fails."
return icon === iconDefault ? nil : icon
}
}