0

这是我正在使用的代码。

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

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

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

我的 file.plist 在我的可可项目的支持文件夹中。mainBundle 在哪里查找文件。这让我很困惑。我知道它会查找 .app 文件,但是在开发应用程序时 mainBundle 会在哪里查找?

4

2 回答 2

2

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

于 2014-02-24T21:43:21.210 回答
1

如果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情况的一种方法。

于 2018-03-29T10:57:40.937 回答