本文介绍了NSBundle pathForResource返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在iOS应用程序的单元测试中加载一个简单的文本文件.

I've been trying to load a simple text file in a unit test for an iOS app.

NSString* resourcePath = [[NSBundle mainBundle] pathForResource: @"stopPointsInCircleData" ofType:@"txt"];
NSString* stopPointData = [NSData dataWithContentsOfFile: resourcePath];

我的问题是pathForResource返回nil.

My problem is that pathForResource returns nil.

文件stopPointsInCircleData.txt位于测试代码的目录中,并且该文件正确列出在测试目标的构建阶段"中的复制捆绑资源"下.

The file stopPointsInCircleData.txt is located in the directory of the test code and the file is listed correctly under "Copy Bundle Resources" in the "Build Phases" of the test target.

我试图通过将ofType设置为nil来放松搜索,但是那也不起作用.

I've tried to relax the search by setting ofType to nil, but thet didn't work either.

非常感谢任何帮助.

推荐答案

您的问题是,在单元测试目标中,-mainBundle不引用测试目标捆绑包,而是引用测试所在的可执行文件的捆绑包目标被注入.对于ios测试目标,这是您的应用程序捆绑包;在Mac测试目标中,它可能是应用程序捆绑包,也可能是OCUnit运行器.

Your problem is that in a unit test target, -mainBundle doesn't refer to the test target bundle but instead to the bundle of the executable in which the test target is injected. In the case of ios test targets, this is your app bundle; in Mac test targets it may either be the app bundle or the OCUnit runner.

您应该在测试目标的捆绑软件中寻找资源.在测试类中,它是这样完成的:

You should look for resources in your test target's bundle. Inside a test class, it's done like this:

NSBundle *myBundle = [NSBundle bundleForClass: [self class]];

这篇关于NSBundle pathForResource返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 06:30