Filed under: iPod Family, How-tos, Developer, iPhone
iPhone Coding: Use NSBundle and avoid hard-coded paths
Listen up, iPhone coders, NSBundle is your friend. It lets you look in your main .app bundle and retrieve files without hardcoding paths. Avoid "/Application/MyProg.app/foo.png" and replace your absolute references with relative ones. This lets your users install your applications wherever they wish.
An NSBundle object locates your app in the local file system so you can access resources and use them in your programs. [NSBundle mainBundle] returns the object for your app. When you use the pathForResource: ofType: inDirectory: method, you can easily find the path to those resources. For example, to find the Default.png file in the top level of an iPhone or iPod touch application, use: [[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png" inDirectory:@""]]. Couldn't be simpler.
Skip the type argument (use @"") for resources without extensions.

Get a WordPress.com Blog
![TUAW [Cafepress]](http://www.blogsmithmedia.com/www.tuaw.com/media/tuaw-cafepress-promo.png)


Reader Comments (Page 1 of 1)
Ross said 7:26PM on 11-13-2007
Erica - you totally need to convince the powers that be that you need a new blog for all of this juicy iphone hacking goodness. Keep up the great posts!
Reply
indiekiduk said 8:08PM on 11-13-2007
For images and UIKit apps there is an easier way:
UIImage* fooImage = [UIImage applicationImageNamed:@"foo.png"];
Reply
Macroy said 8:11PM on 11-13-2007
#1: Whaaa? A politely-written request about a separate iPhone-hacking section?! What site do you think you're on?!
Reply
Patrick McCarron said 9:38PM on 11-13-2007
Thanks to Erika and indiekiduk. I have been using NSBundles since day 1, seemed way to smart not to. But have now been wondering how to pull files from /private/var/root/ for an add-on I'm going to do for my App. I didn't know of the inDirectory function, but I hadn't dug thru the headers yet.
Reply
tragiclos said 10:40PM on 11-13-2007
Slight correction:
[[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png" inDirectory:@""]]
should be:
[[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png" inDirectory:@""]
Reply
Garry Schafer said 12:03AM on 11-14-2007
Erica - would you ever consider a cocoa tutorials site, or one on the iPhone? Seriously. From a programmer of many years somewhat scared by objective c
Reply
boz said 10:53AM on 11-14-2007
So, I take this post to mean there are actually people out there writing apps for iPhone that don't already know about NSBundle?
That is a scary thought and doesn't bode well for the quality of software being written for iPhone right now.
Reply
ymilord said 11:53AM on 11-14-2007
I love it when you talk dirty. [o_O]
Reply