设想:

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

# 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:documentation states that UTI can be used



定制解决方案:

我编写了以下帮助程序方法以从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())

问题:
  • 您知道提取内容类型信息的更明智的方法
    Info.plist文件?有 cocoa 内置功能吗?
  • 您如何处理可以包含的文件夹的定义
    在那里public.folder

  • 注意:
    在我的整个研究过程中,我发现这篇文章内容丰富:Simplifying Data Handling with Uniform Type Identifiers

    最佳答案

    这是我从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"];
    

    关于objective-c - 从plist检索允许的文件类型的明智方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7569672/

    10-11 22:08
    查看更多