NSBundle是什么

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 optional
NSString *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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值