pathForResource ofType返回nil

时间:2014-02-24 21:34:13

标签: objective-c null nsbundle mainbundle

这是我正在使用的代码。

NSString* path = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"plist"];

if(path == nil)
{
NSLog(@"file not found");
}

当我运行它时会打印出在控制台中找不到的文件。

我的file.plist在我的可可项目的支持文件文件夹中。 mainBundle在哪里查找文件。这让我很难受。我得到它寻找.app文件,但在开发doe mainBundle看起来的应用程序时?

2 个答案:

答案 0 :(得分:2)

pathForResource:ofType:仅查看Resources文件夹(和本地化文件夹)。如果要将文件放入捆绑包中的专用文件夹,则需要使用pathForResource:ofType:inDirectory:并提供目录名称。

答案 1 :(得分:0)

如果您找到的NSBundle是您想要的:

NSBundle *yourTargetBundle = [NSBundle mainBundle];

or

NSBundle *yourTargetBundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] 
URLForResource:@"YourCustomBundleName" withExtension:@"bundle"]];

获取nil结果使用函数:pathForResource: ofType:。然后,您可以在paths下记录yourTargetBundle资源:

// Given that your resource type is .png and have no sub dir
NSArray *resoursePaths = [yourTargetBundle pathsForResourcesOfType:@"png" inDirectory:nil];
NSLog(@"resoursePaths == %@",resoursePaths);

它将记录png类型的所有资源路径。您可以使用image对象:

targetImg = [[UIImage alloc] initWithContentsOfFile:@"OnePngPathYouChose"];

我认为上述方法是解决return nil情况的一种方法。

相关问题