从plist中检索允许的文件类型的智能方法

JJD*_*JJD 9 cocoa content-type objective-c uti nssavepanel

场景:

我喜欢在Info.plist我的Cocoa应用程序的文件中定义允许的文件类型(内容类型).因此,我添加了它们,如下面的示例所示.

# Extract from Info.plist
[...]
<key>CFBundleDocumentTypes</key>
<array>
    <dict>
        <key>CFBundleTypeName</key>
        <string>public.png</string>
        <key>CFBundleTypeIconFile</key>
        <string>png.icns</string>
        <key>CFBundleTypeRole</key>
        <string>Viewer</string>
        <key>LSIsAppleDefaultForType</key>
        <true/>
        <key>LSItemContentTypes</key>
        <array>
            <string>public.png</string>
        </array>
    </dict>
[...]
Run Code Online (Sandbox Code Playgroud)

此外,我的应用程序允许使用NSOpenPanel.打开文件.面板允许通过以下选择器设置允许的文件类型:setAllowedFileTypes:.该文件指出,UTI可以使用.

文件类型可以是公共文件扩展名,也可以是UTI.


自定义解决方案:

我编写了以下帮助方法来从Info.plist文件中提取UTI .

/**
    Returns a collection of uniform type identifiers as defined in the plist file.
    @returns A collection of UTI strings.
 */
+ (NSArray*)uniformTypeIdentifiers {
    static NSArray* contentTypes = nil;
    if (!contentTypes) {
        NSArray* documentTypes = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDocumentTypes"];
        NSMutableArray* contentTypesCollection = [NSMutableArray arrayWithCapacity:[documentTypes count]];
        for (NSDictionary* documentType in documentTypes) {
            [contentTypesCollection addObjectsFromArray:[documentType objectForKey:@"LSItemContentTypes"]];
        }
        contentTypes = [NSArray arrayWithArray:contentTypesCollection];
        contentTypesCollection = nil;
    }
    return contentTypes;
}
Run Code Online (Sandbox Code Playgroud)

而不是[NSBundle mainBundle]CFBundleGetInfoDictionary(CFBundleGetMainBundle())可以使用.


问题:

  1. 您是否知道从Info.plist文件中提取内容类型信息的更智能方法?是否有Cocoa-build-in功能?
  2. 你如何处理那里可以包含的文件夹的定义,例如public.folder

注意:
在我的研究中,我发现这篇文章非常有用:用统一类型标识符简化数据处理.

Sco*_*ood 1

以下是我从 plist 中读取信息的方法(它可以是 info.plist 或项目中的任何其他 plist,前提是您设置了正确的路径)

NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *fullPath = [NSString stringWithFormat:@"%@/path/to/your/plist/my.plist", resourcePath];
NSData *plistData = [NSData dataWithContentsOfFile:fullPath];
NSDictionary *plistDictionary = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:0 errorDescription:nil];
NSArray *fileTypes = [plistDictionary objectForKey:@"CFBundleDocumentTypes"];
Run Code Online (Sandbox Code Playgroud)