1.27. Loading Data From the Main Bundle
Problem
You have added a resource (such as an image) to your Xcode project and now, at runtime, you would like to access that resource.
Solution
Use the mainBundle class
method of the NSBundle class in
order to retrieve your main bundle. Once that is done, use the
pathForResource:ofType: method of your main
bundle to retrieve the path for that specific resource. Once the path
is detected, depending on the type of resource, you can either pass
the path to your file to a class such as UIImage or NSData, or you can manually access the file
using NSFileManager.
Note
It is required that you give a unique name to each resource inside your main bundle. For instance, it is not good practice to have a file named Default.png in more than one place inside your main bundle. Different ways of loading a resource from a bundle could then yield different results. As a result, make sure you give unique names to your files inside any bundle, regardless of whether it is the main bundle or a custom bundle that you’ve created (see Recipe 1.26).
Discussion
To access the main bundle, we can use the mainBundle class method of the NSBundle class. Bundles are all of type
NSBundle and once you have an
instance of a bundle, you can load resources from that bundle.
Note
Every app’s main bundle has a flat hierarchy on disk when it is compiled for submission to App Store. That means all the files that get wrapped up in your app bundle will be placed on the root folder of the main ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access