iOS--NSBundle理解

时间:2023-03-08 22:27:21

NSBundle:官方文档解释:
An
NSBundle object represents a location in the file system that groups
code   and resources that can be used in a program. NSBundle objects
locate program resources, dynamically load and unload executable code,
and assist in localization. You build a bundle in Xcode using one of
these project types: Application, Framework, plug-ins.
大概翻译过来:
NSBundle 对象指代相应应用程序下的所有可用的文件系统。就是说,可以用NSBundle操作应用程序下,所有可用的资源(包括,xib文件,数据文件,图片 等)。

NSBundle 英语中的解释是:“捆,束”的意思,那我们可以理解为:
NSBundle是将程序中所有资源捆在一起的对象。

//bundle实际上是一个目录,其中包含了程序会使用的资源,包括:图像,声音,编译好的代码,nib文件等,cocoa中对应的类是NSBundle Carbon中对应的是CFBundleRef
    
    NSBundle *bundle = [NSBundle mainBundle];
    NSLog(@"mainBundlePath=%@",[bundle bundlePath]);
    
    //使用bundle类可以访问该项目中的所有资源,mainBundle对应的是该项目的根目录,想要获取其中的资源,需要使用对应的方法
    
    //如果该路径为NULL,说明该路径下找不到指定的资源 一个路径对应着一个资源文件,然后根据path或者url把文件读入到内存里
    NSString *path = [bundle pathForResource:@"image" ofType:@"jpg"];
    NSLog(@"imagePath=%@",imagePath);
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];
    NSLog(@"imageDescription=%@",[image description]);
    NSLog(@"image size=%li",[image size]);


前在初始化一个类的时候:ViewController *viewcontroller=[[ViewController
alloc]initWithNibName:@"ViewController" bundle:[NSBundle
mainBundle]];不是很明白:[NSBundle mainBundle]的意思。后来查阅资料后知道了它的作用,如下:
       
 bundle是一个目录,其中包含了程序会使用到的资源.
这些资源包含了如图像,声音,编译好的代码,nib文件(用户也会把bundle称为plug-in).
对应bundle,cocoa提供了类NSBundle.我们的程序是一个bundle.
在Finder中,一个应用程序看上去和其他文件没有什么区别. 但是实际上它是一个包含了nib文件,编译代码,以及其他资源的目录.
我们把这个目录叫做程序的main bundle。
通过使用下面的方法得到程序的main bundle


NSBundle *bundle = [NSBundle mainBundle];
一般我们通过这种方法来得到bundle.如果你需要其他目录的资源,可以指定路径来取得bundle


NSBundle *bundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];
一旦我们有了NSBundle 对象,那么就可以访问其中的资源了
NSBundle束,是一种特定的文件类型,其中的内容遵循特定的结构。
NSBundle的一个主要作用是 获取Resources文件夹中的资源。
 
       
在编程中使用[NSData
dataWithContentOfFile:@“image”]的时候,总是无法读取正确的文件内容。而使用[NSData
dataWithContentOfFile:[[NSBundle mainBundle] pathForResource:@”image”
ofType:@“”]的时候就可以。

因为当使用相对路径的时候,其实他相对的当前目录并不是程序运行的目录,而是“/”。只有使用[NSBundle mainBundle]来生成的路径才是文件真正的路径。