我有这个代码
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。
我有这个代码
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。
以下内容应该适用于在至少 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 中的(未记录的?)扩展;除非您发现它已记录在案,否则最好避免使用它。
此解决方案适用于两种操作系统):
[[NSBundle mainBundle] pathForResource:[[path pathComponents] lastObject]
ofType:nil
inDirectory:[path stringByDeletingLastPathComponent]];
注意:lastObject
并且stringByDeletingPathComponents
在这种情况下很好,因为不会因索引超出范围而崩溃,而是返回 nil!
最初我认为这会成功,但事实并非如此:
[[NSBundle mainBundle] pathForResource:nil ofType:nil inDirectory:path];
这将返回在路径(文件或文件夹)中找到的第一个元素,这完全不是我想要的。
我猜Apple“调整”了pathForResource:ofType:
自 10.8 以来的实现,使其也可以与目录一起使用,因此根据您是否仍然需要支持 10.7,您知道应该使用什么。
也许我遗漏了一些明显的东西,比如一种更简单的取回目录的方法(同样,在 10.7 中,因为在 10.8 中它非常容易,就像我在问题中所说的那样)。