Search code examples
iosobjective-cipadfilesystemsnsbundle

NSBundle mainBundle pathForResource: Not working unless @2x included


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


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.