Monday, November 9, 2009

How to access resources in the main bundle.

The app I'm working has images embedded in the bundle; they may be JPG or PNG. Trying to find a path those resources can be done in one of three possible ways, as far as I see right now:

1) NSString *imgPath = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] bundlePath], nameOfImage];

#1 is what I ended up using, since that's exactly where the images are located and I don't have to be concerned about the type of the image.

2) NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0]; // And add as part of a formatted string, like in item 1.

#2 was a side path I took, forgetting that you have to add the references as part of a folder structure (which I'm not completely clear on at this time)

3) NSString *jpgPath = [[NSBundle mainBundle] pathForResource:nameOfImage ofType:@"jpg"];

#3 was the way I was recently taught, but the it always bothered me that there was an "ofType" message. How can you rest assured that the image type will ALWAYS be of that type. I'd have to do a bit of extra work (pulling from a plist, or database, or parsing the image name) to ensure I had the proper resource type. And since images are, very generally speaking, interchangeable (at least as far as my content developers are concerned!), I feel this is a case where it pays to be more flexible, so #3 just doesn't work for me (in this situation).

No comments: