Search code examples
objective-cxcodepngfilenamesnsbundle

How to get the PNG name instead of the whole directory path in Xcode?


So I have a list of PNG's in my "Supporting Files" Xcode project. And I did this to access all files with extension PNG:

NSArray *pngFilePaths = [[NSBundle mainBundle] pathsForResourcesOfType:@"png" inDirectory:@""];
NSLog(@"PNG:%@", pngFilePaths);

That prints out this:

"/Users/John/Library/Application Support/iPhone Simulator/5.1/Applications/123456-1234-1234-1234-B123412341234/MyPNGProject.app/UI_daily_time.png"

However, I only want the PNG NAME "UI_daily_time", instead of the whole path. So I just added the directory above to get to the png with this:

NSArray *pngFilePaths = [[NSBundle mainBundle] pathsForResourcesOfType:@"png" inDirectory:@"/Users/John/Library/Application Support/iPhone Simulator/5.1/Applications/123456-1234-1234-1234-B123412341234/MyPNGProject.app/"];
NSLog(@"PNG:%@", pngFilePaths);

But pngFilePaths is now empty, I'm guessing the "inDirectory" path I gave it is wrong, but I don't know why. Any help is much appreciated, thanks in advance!


Solution

  • Once you get the full path use stringByDeletingPathExtension to get rid of the extension, then use lastPathComponent to get the name only:

    NSString *pngFilePath = [pingFilePaths objectAtIndex:0];
    NSString *pngName = [[pngFilePath stringByDeletingPathExtension] lastPathComponent];