iphone development NSBundle pathForResource load images from subfolder problem

本文解析了在Xcode中使用NSBundle方法pathForResource寻找资源文件时常见的误区。指出开发者在项目面板看到的“Resources”和“Images”文件夹实际上并非真实存在于磁盘上,而是Xcode的一种虚拟分组方式。因此,在指定子目录时需谨慎,避免因误解该方法的行为而导致找不到文件。

+ (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)bundlePath;

- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext;

- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)subpath;

 

I was fucked by this method today, some guy said it's a bug, eventually I found it's not a bug.

 

We see Resources/Images folder in project panel in XCode,  yes we do see it existing, but if you open your project folder on your hardware, you'll see neither "Resources" folder nor "Images" folder, and the images are exhibited in root

folder of your project, that's why the following is wrong:

 

NSString *resource = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"png" inDirectory: @"images"];

 

instead if you have this folder “images" in your hardware, you could use above method. otherwise let's 

use below one:

 

NSString *resource = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"png" inDirectory: @""];

or

NSString *resource = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"png"];

 

The REASON is the "Resources" and "images" folder is just a "SOFT" group structure we saw in XCode, they are not mapping to real folder on hardware, so the compiled app doesn't include this "SOFT" folder structure, then you can't find that file in subfolder.

 

原因就是我们看到的文件夹结构并不是实际的硬盘上的文件夹结构,所以编译完成的iphone应用程序的bundle里没有这个组织结构。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值