Question

I have files named: landing_load1@2x ...landing_load4@2x in my project. (No non-retina files)

This code works:

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

    [loadingImages addObject:loadingImage];
}

But this doesn't work:

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];
}

And this doesn't work:

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];
}

Question: I know I don't have to explicitly call @2x or specify the file type, so any ideas why it's not working unless I explicitly write the whole file name out?

Note: Tested on iPad 4

Was it helpful?

Solution

Record

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

means that you have a pair of graphics files for any resource - both "filename.png" and "filename@2x.png". Or, alternatively, it can be used as "alias" for only "filename.png" If you have only "filename@2x.png", you have two possible variants: 1. Use something like that

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

or have both of files ("filename.png" and "filename@2x.png") for any resource.

OTHER TIPS

In the 'non' working example you haven't stated nil in the ofType parameter.

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

change to png, should do the trick :)

Because you are using

-[NSBundle pathForResource:ofType:]

method, you need to specify resource type in second parameter, which you were provided as "png" in the code you say it works.

The @2x is handled as part of [UIImage imageNamed:] not as a part of [NSBundle pathForResource:ofType:] Just use the former and you should be good to go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top