Bundle is a directory that contains the resources used by the program. these resources contain images, sounds, compiled code, and nib files (bundle is also called plug-in ). corresponding bundle. Cocoa provides the nsbundle class.
Our program is a bundle. in the finder, an application looks no different from other files. but it is actually a directory that contains nib files, compiled code, and other resources. we call this directory the main bundle of the program.
Some resources in bundle can be localized. for example, for foo. NIB, we can have two versions: one for English users and one for French users. the bundle contains two subdirectories: English. lproj and French. lproj. place the NIB file in it. when the program needs to load Foo. when a NIB file is created, the bundle is automatically loaded based on the language specified. we will discuss localization in detail in chapter 16
Use the following method to obtain the main bundle of the program.
NSBundle *myBundle = [NSBundle mainBundle];
This method is usually used to obtain bundle. If you need resources from other directories, you can specify a path to obtain bundle.
NSBundle *goodBundle;
goodBundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];
Once we have an nsbundle object, we can access the resources in it.
// Extension is optional
NSString *path = [goodBundle pathForImageResource:@"Mom"];
NSImage *momPhoto = [[NSImage alloc] initWithContentsOfFile:path];
Bundle can contain a library. If we get a class from the library, bundle connects to the library and looks for 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 to obtain
Class aClass = [goodBundle principalClass];
id anInstance = [[aClass alloc] init];
As you can see, nsbundle has many functions. In this chapter, nsbundle is responsible for loading nib files (in the background). We can also directly use nsbundle instead of nswindowcontroller to load nib files:
BOOL successful = [NSBundle loadNibNamed:@"About" owner:someObject];
Note: We have specified an object someobject as the file "s owner of nib.
Get XML file
NSString *filePath = [[NSBundle mainBundle] pathForResouse:@"re" ofType:@"xml"];
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
Get attribute list
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ViewControllers" ofType:@"plist"]];