9

设想:

我喜欢在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>
[...]

此外,我的应用程序允许使用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;
}

代替[NSBundle mainBundle]CFBundleGetInfoDictionary(CFBundleGetMainBundle())可以使用。


问题:

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

注意:
在我的研究中,我发现这篇文章信息量很大:使用统一类型标识符简化数据处理

4

1 回答 1

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"];
于 2011-11-05T01:11:17.090 回答