访问OCUnit测试目标中的UIImage

tre*_*eba 13 iphone unit-testing objective-c ocunit ipad

我正在为iPad应用程序编写图像处理测试.我的单元测试目标中有一个资源文件夹,里面有一张照片,但是当我尝试使用[UIImage imageNamed:@"photo1.jpg"]访问它时,没有返回任何图像.如果我将文件名更改为主资源文件夹中的文件名,则会返回图像.

有没有办法访问单元测试目标内的Resources文件夹?

tre*_*eba 23

找到了这个答案,看起来你不能使用[UIImage imageNamed:],你可以像这样访问图像:

NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString *imagePath = [bundle pathForResource:@"photo1" ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
Run Code Online (Sandbox Code Playgroud)


Jos*_*ord 12

从iOS 8开始,我们有:-imageNamed:inBundle:compatibleWithTraitCollection:方法UIImage

在Swift中:

let bundle = NSBundle(forClass: self.dynamicType)
let image:UIImage? = UIImage(named: "imageFileName",
                          inBundle:bundle,
     compatibleWithTraitCollection:nil)
Run Code Online (Sandbox Code Playgroud)

在Objective-C中

NSBundle* bundle = [NSBundle bundleForClass:[self class]];
UIImage* image = [UIImage imageNamed:@"imageFileName.extension"
                             inBundle:bundle
        compatibleWithTraitCollection:nil];
Run Code Online (Sandbox Code Playgroud)