NSBundle是什么

来源:互联网 发布:视频美容软件 编辑:程序博客网 时间:2024/06/06 03:32

NSBundle

bundle is a directory of resources that may be used by an application. Resources include such things as images, sounds, compiled code, and nib files. (Users often use the word plug-in instead of bundle.) The class NSBundle is a very elegant way of dealing with bundles.

Your application is a bundle. In Finder, an application looks to the user like any other file, but it is in fact a directory filled with nib files, compiled code, and other resources. We call this directory the main bundle of the application.

Some resources in a bundle can be localized. For example, you could have two versions of foo.nib: one for English speakers and one for French speakers. The bundle would have two subdirectories: English.lproj and French.lproj. You would put an appropriate version of foo.nib in each. When your application asks the bundle to load foo.nib, the bundle will automatically load the French version of foo.nib if the user set the preferred language to French. We cover localization in Chapter 16.

To get the main bundle of an application, use the following code:

NSBundle *myBundle = [NSBundle mainBundle];

This is the most commonly used bundle. If you need to access resources in another directory, however, you could ask for the bundle at a certain path:

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

Once you have an NSBundle object, you can ask it for its resources:

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

A bundle may have a library of code. If you ask for a class from the bundle, the bundle will link in the library and search for a class by that name:

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

If you do not know the name of any classes in the bundle, you can simply ask for the principal class:

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

As you see, NSBundle is handy in many ways. In this section, the NSBundle was responsible (behind the scenes) for loading the nib file. If you wanted to load a nib file without an NSWindowController, you could do it like this:

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

Note that you would supply the object that will act as File's Owner.