【问题标题】:- [NSBundle pathForResource:ofType] works differently for directories on 10.7 and 10.8- [NSBundle pathForResource:ofType] 对 10.7 和 10.8 上的目录的工作方式不同
【发布时间】:2013-09-07 22:57:05
【问题描述】:

我有这个代码

NSString *path = @"foo/bar"; // Note this is a directory, not a file!
NSString *pathInBundle = [[NSBundle mainBundle] pathForResource:path ofType:nil];

它在 10.8 上运行良好(返回在包中找到的路径),但在 10.7 中返回 nil。

【问题讨论】:

    标签: objective-c macos cocoa appkit nsbundle


    【解决方案1】:

    此解决方案适用于两种操作系统):

    [[NSBundle mainBundle] pathForResource:[[path pathComponents] lastObject]
                                    ofType:nil
                               inDirectory:[path stringByDeletingLastPathComponent]];
    

    注意:lastObjectstringByDeletingPathComponents 在这种情况下很好,因为不会因索引超出范围而崩溃,而是返回 nil!

    本来我以为这样就可以了,但它确实不是

    [[NSBundle mainBundle] pathForResource:nil ofType:nil inDirectory:path];
    

    这会返回在路径中找到的第一个元素(文件或文件夹),这完全不是我想要的。

    我猜 Apple 从 10.8 开始“调整”了 pathForResource:ofType: 的实现,使其也可以与目录一起使用,因此根据您是否仍需要支持 10.7,您知道应该使用什么。

    也许我遗漏了一些明显的东西,比如更简单的取回目录的方法(同样,在 10.7 中,因为在 10.8 中它非常容易,就像我在问题中所说的那样)。

    【讨论】:

      【解决方案2】:

      以下内容应该适用于在至少 10.6 -> 10.8 中找到捆绑包子目录中任何项目的路径,包括适当的本地化变体:

      // long hand...
      NSString *item = [path lastPathComponent];                          // path/item -> item
      NSString *itemBase = [item stringByDeletingPathExtension];          // base[.ext] -> base
      NSString *itemExtension = [item pathExtension];                     // base[.ext] -> ext or @""
      NSString *pathDirectory = [path stringByDeletingLastPathComponent]; // path/item -> path
      NSString *pathInBundle = [[NSBundle mainBundle] pathForResource:itemBase
                                                               ofType:itemExtension
                                                          inDirectory:pathDirectory];
      

      允许pathForResource: 成为路径似乎是 10.8 中的(未记录的?)扩展;除非您发现它已记录在案,否则最好避免使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-08
        • 2014-03-12
        • 2012-06-04
        相关资源
        最近更新 更多