NSBundle mainBundle pathForResource:不工作,除非@ 2x包括

问题描述:

我的文件名为:landing_load1 @ 2x ... landing_load4 @ 2x在我的项目中。 (没有非视网膜文件)NSBundle mainBundle pathForResource:不工作,除非@ 2x包括

此代码:

for(int x=1; x < 5; x++){ 
    NSString * imageTitle = [NSString stringWithFormat:@"landing_load%[email protected]", x]; 
    UIImage * loadingImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageTitle ofType:@"png"]]; 

    [loadingImages addObject:loadingImage]; 
} 

但是,这并不工作:

for(int x=1; x < 5; x++){ 
    NSString * imageTitle = [NSString stringWithFormat:@"landing_load%i", x]; 
    UIImage * loadingImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageTitle ofType:nil]]; 

    [loadingImages addObject:loadingImage]; 
} 

而且这不起作用:

for(int x=1; x < 5; x++){ 
     NSString * imageTitle = [NSString stringWithFormat:@"landing_load%i", x]; 
     UIImage * loadingImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageTitle ofType:nil]]; 

    [loadingImages addObject:loadingImage]; 
} 

问题:我知道我不必显式调用@ 2x或指定文件类型,所以任何想法为什么它不工作,除非我明确写出整个fi列出来?

注:测试的iPad 4

记录

NSString * imageTitle = [NSString stringWithFormat:@"landing_load%i", x]; 

意味着你有一对图形文件的任何资源 - 无论是“filename.png”和“[email protected]”。 ,或者,它可以被用来作为“别名”只对“filename.png” 如果只有“[email protected]”,你有两种可能的变体: 1.使用类似的东西

NSString * imageTitle = [NSString stringWithFormat:"landing_load%[email protected]", x]; 

或同时拥有任何资源的文件(“filename.png”和“[email protected]”)。

在“非”工作例如,你有没有在ofType参数说明nil

UIImage * loadingImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]  pathForResource:imageTitle ofType:nil]]; 

变化png,因为你正在使用

-[NSBundle pathForResource:ofType:] 

方法应该做的伎俩:)

+1

更新了问题。除非添加@ 2x,否则仍然不起作用。谢谢 – user3456115

,你需要指定第二个参数,你被设置为“资源类型PNG“你说它的工作原理。

@ 2x是作为[UIImage imageNamed:]的一部分处理的,而不是作为[NSBundle pathForResource:ofType:]的一部分。只要使用前者,你应该很好。

+1

imageNamed不释放图像并导致内存问题 – hasan83