简体   繁体   English

访问单个文件的元数据

[英]Access metadata of a single file

Is there a way to programmatically access metadata of a single file on MacOS? 有没有办法以编程方式访问MacOS上单个文件的元数据?

I know Apple provides NSMetadataQuery , but it seems it only allows to search in particular folders for files matching some parameters. 我知道Apple提供了NSMetadataQuery ,但它似乎只允许在特定文件夹中搜索与某些参数匹配的文件。 Actually I'd prefer not to search for all files matching but check if a particular file matches. 实际上我不想搜索匹配的所有文件,但检查特定文件是否匹配。

Is there a way or the only solution is to analyze the results of the query and see if my file is among them? 有没有办法或唯一的解决方案是分析查询的结果,看看我的文件是否在其中?

You can get the metadata the same way the command mdls gets its data. 您可以使用与命令mdls获取其数据相同的方式获取元数据。 Search for MDItemCreate in the documentation. 在文档中搜索MDItemCreate (you find : Core Library --> Data Management --> File Management --> MDItem Reference ) (您会发现: 核心库 - >数据管理 - >文件管理 - > MDItem参考
I hope the following method to create the metadata dictionary will give you what you need: 我希望以下创建元数据字典的方法能够满足您的需求:

- (NSDictionary *) metaDataDictionaryForFileAt:(NSString *)fileName
{
    MDItemRef item = MDItemCreate( kCFAllocatorDefault, (CFStringRef)fileName );
    if( item==nil ) return nil;

    CFArrayRef list = MDItemCopyAttributeNames( item );
    NSDictionary *resDict = (NSDictionary *)MDItemCopyAttributes( item, list );
    CFRelease( list );
    CFRelease( item );
    return [resDict autorelease];
}

Remark : The value of kMDItemContentType , kMDItemContentTypeTree , and kMDItemKind are determined by the suffix of the filename not by the content of the file! 备注kMDItemContentTypekMDItemContentTypeTreekMDItemKind的值由文件名的后缀而不是文件的内容决定!

I don't think there's an API for this (which is odd, you should file a bug). 我不认为这有一个API(这很奇怪,你应该提交一个bug)。 If you don't want to run a query then your only other option would be to use NSTask to spawn an instance of the mdls command and then parse the results. 如果您不想运行查询,那么您唯一的另一个选择是使用NSTask生成mdls命令的实例,然后解析结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM