Nsbundle introduction


Bundle is a directory that contains the resources that the program will use. These resources include images, sounds, compiled code, nib files (the user will also call the bundle plug-in). Corresponding to the bundle, cocoa provides the class nsbundle

Our program is a bundle. In finder, an application looks no different from other files. But in fact, it is a directory containing NIB files, compiled code, and other resources. We call this directory the main bundle of the program

Some resources in the bundle can be localized. For example, for foo.nib We can have two versions: one for English users and one for French users English.lproj and French.lproj We put our own versions of foo.nib When the program needs to be loaded foo.nib When you file, The bundle will be loaded automatically according to the language set. We will discuss localization in detail in Chapter 16

Use the following method to get the main bundle of the program

NSBundle *myBundle = [NSBundle mainBundle];

If you need resources from other directories, you can specify the path to get the bundle

NSBundle *goodBundle;
goodBundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];

Once we have the nsbundle object, we can access the resources in it

// Extension is optional
NSString *path = [goodBundle pathForImageResource:@"Mom"];
NSImage *momPhoto = [[NSImage alloc] initWithContentsOfFile:path];

The bundle can contain a library. If we get a class from the library, the bundle will connect to the library and find the class:

Class newClass = [goodBundle classNamed:@"Rover"];
id newInstance = [[newClass alloc] init];

If you do not know the class name, you can also find the main class

Class aClass = [goodBundle principalClass];
id anInstance = [[aClass alloc] init];

As you can see, nsbundle has many uses. Among them, nsbundle is responsible for loading NIB files (in the background). We can also use nsbundle directly instead of loading NIB files through nswindowcontroller

BOOL successful = [NSBundle loadNibNamed:@"About" owner:someObject];

Note that we have specified an object someobject as NIB’s file’s owner

When using initwithcontentsoffile, the file path is written. Using the initwithcontentsoffile method, you can initialize an object by reading the contents of a file.

But how to determine the file path? You can use the nsbundle object to get it.

For example, there is a file in the current program directory re.xml To initialize an nsdata object by using the contents of this file as the data source of nsdata, we can use the following methods to implement it:

NSString *filePath = [[NSBundle mainBundle] pathForResouse:@"re" ofType:@"xml"]; 
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];