NSBundle官方文档

  1. 获取Main Bundle

main bundle表示正在运行的app中所包含的code和resources。如果你是app开发者,这个是最常用的bundle。main bundle也是最简单获取的bundle因为它不需要提供任何信息。

mainBundle = [NSBundle mainBundle];

或者通过Core Foundation来获取,如果你在写一个基于C的APP的话:

mainBundle = CFBundleGetMainBundle();
  1. 通过Path获取Bundles

如果你想访问一个非mainBundle的bundle,那么你可以创建一个合适的bundle对象,如果你知道这个bundel的路径的话。

myBundle = [NSBundle bundleWithPath:@"/Library/MyBundle.bundle"];
CFURLRef bundleURL;
CFBundleRef myBundle;

// Make a CFURLRef from the CFString representation of the
// bundle’s path.
bundleURL = CFURLCreateWithFileSystemPath(
                kCFAllocatorDefault,
                CFSTR("/Library/MyBundle.bundle"),
                kCFURLPOSIXPathStyle,
                true );

// Make a bundle instance using the URLRef.
myBundle = CFBundleCreate( kCFAllocatorDefault, bundleURL );

// You can release the URL now.
CFRelease( bundleURL );

// Use the bundle...

// Release the bundle when done.
CFRelease( myBundle );

  1. 通过Identifier找到Bundle:
    通过bundle identifier来锁定bundles是一个有效的方法,并且这种方法会让bundle提前加载到内存中。
    例如:
NSBundle* myBundle = [NSBundle bundleWithIdentifier:@"com.apple.myPlugin"];

如果要通过Core Foundation来使用identifier锁定bundle要用以下方式:

CFBundleRef requestedBundle;
 // Look for a bundle using its identifier
 requestedBundle = CFBundleGetBundleWithIdentifier(
        CFSTR("com.apple.Finder.MyGetInfoPlugIn") );

记住,你只可以通过bundle idenditfier来找已经打开了的bundle。你不能使用这个方法来引用一个还没有被load的插件。

  1. 想要在特殊的设备上加载文件资源,需要在文件名上加上特殊的自定义字符串。格式如下:
.
  • basename代表了资源的原始名称;
  • extension代表了文件的扩展名;
  • device字符串可以为以下值:
    ~ipad,资源只能被iPad设备加载;
    ~iphone,资源只能被iPhone或者iPod touch设备加载

加载资源时,你可以指定资源为MyImage。png,让系统选择合适的版本,例如:

UIImage* anImage = [UIImage imageNamed:@"MyImage.png"];

在iPhone或者iPod touch上,系统会加载MyImageiphone.png资源;在iPad上,MyImageipad.png资源文件会被加载。如果指定了设备的版本没有被发现,那么系统会回过去找原始filename的版本,在例子中就是MyImage.png.

你可能感兴趣的:(NSBundle官方文档)