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.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: