资源 return 的 NSBundle 路径在 iOS 中为零
NSBundle path for resource return nil in iOS
我有一个 bgs.bundle
,其中包含 20 张图片,我正在尝试加载 image_file。
NSString *bpath = [[NSBundle mainBundle] pathForResource:@"bgs" ofType:@"bundle"];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bpath error:NULL];
for (NSString *fileName in files) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"nil"];
if (filePath){
NSLog(filePath);
}else{
NSLog(@"file path is null");
}
filePath
始终为空,我还打印了 fileName
,效果很好。
我的代码可能有什么问题,或者有其他方法可以从包中加载文件?
你的主要问题是你试图从主包而不是 bgs.bundle
加载 fileName
。
像这样更改您的代码:
NSString *bpath = [[NSBundle mainBundle] pathForResource:@"bgs" ofType:@"bundle"];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bpath error:NULL];
for (NSString *fileName in files) {
NSString *filePath = [bpath stringByAppendingPathComponent:fileName];
NSLog(@"filePath = %@", filePath);
}
另一种选择是为 bgs.bundle
获得 NSBundle
。
NSString *bpath = [[NSBundle mainBundle] pathForResource:@"bgs" ofType:@"bundle"];
NSBundle bgsBundle = [NSBundle bundleWithPath:bpath];
现在您可以根据需要使用bgsBundle
。示例:
NSString *filePath = [bgsBundle pathForResource:@"someImage" ofType:@"png"];
我有一个 bgs.bundle
,其中包含 20 张图片,我正在尝试加载 image_file。
NSString *bpath = [[NSBundle mainBundle] pathForResource:@"bgs" ofType:@"bundle"];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bpath error:NULL];
for (NSString *fileName in files) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"nil"];
if (filePath){
NSLog(filePath);
}else{
NSLog(@"file path is null");
}
filePath
始终为空,我还打印了 fileName
,效果很好。
我的代码可能有什么问题,或者有其他方法可以从包中加载文件?
你的主要问题是你试图从主包而不是 bgs.bundle
加载 fileName
。
像这样更改您的代码:
NSString *bpath = [[NSBundle mainBundle] pathForResource:@"bgs" ofType:@"bundle"];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bpath error:NULL];
for (NSString *fileName in files) {
NSString *filePath = [bpath stringByAppendingPathComponent:fileName];
NSLog(@"filePath = %@", filePath);
}
另一种选择是为 bgs.bundle
获得 NSBundle
。
NSString *bpath = [[NSBundle mainBundle] pathForResource:@"bgs" ofType:@"bundle"];
NSBundle bgsBundle = [NSBundle bundleWithPath:bpath];
现在您可以根据需要使用bgsBundle
。示例:
NSString *filePath = [bgsBundle pathForResource:@"someImage" ofType:@"png"];