Bundle文件的创建和使用(一)

经常会出现某个需求:将自己的模块或者开放类,封装成静态库给其他人提供方便的调用。

但是当你的模块中需要大量使用xib,图片,音频或者其他资源文件时,无法添加至静态库。这个时候就需要将一些资源文件封装至.Bundle文件中。那么封装好的东西应该含有三类文件:

1:开放的头文件(包含完整的调用注释)

2:静态库文件 后缀名为.a

3:Bundle文件,用于存放各种资源文件。

 那么其他的都很简单:这里具体说说bundle文件的封装(其实也很简单)

第一步:创建Bundle项目

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 选择Bundle文件类型后并创建项目。

 第二步:修改BuildSetting相关设置

1:Base SDK 修改为 iOS6 或者其他存在的iOS SDK版本

2:Architectures   修改为 armv7 armv7s

 

 

 

第三步:添加需要添加的资源文件

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

第四步:Build (这里不需要使用证书也可以编译成功)

 

 



这样就生成了自己的Bundle

 

调用的时候助需要引用至项目中就行,如下:

程序中引入方式:

 1 获得bundle中的资源
 2 
 3 NSString * bundlePath = [[ NSBundle mainBundle] pathForResource: @ "MyBundle" ofType :@ "bundle"];
 4 NSBundle *resourceBundle = [NSBundle bundleWithPath:bundlePath];
 5 UIViewController *vc = [[UIViewController alloc] initWithNibName:@"vc_name" bundle:resourceBundle];
 6 
 7 图片获得bundle中的资源
 8 
 9 UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
10 UIImage *image = [UIImage imageNamed:@"MyBundle.bundle/img_collect_success"];
11 [imgView setImage:image];
12 
13 或者
14 
15 UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
16 NSString *imgPath= [bundlePath stringByAppendingPathComponent :@"img_collect_success.png"];
17 UIImage *image_1=[UIImage imageWithContentsOfFile:imgPath];
18 [imgView setImage:image_1];
19 
20 当然,可以写成预编译语句:
21 #define MYBUNDLE_NAME @ "MyBundle.bundle"
22 #define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
23 #define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]

 

如果想要将在某个非mainBundle的地方调用。那么需要额外加载此Bundle

posted @ 2015-07-28 15:06  星语海蓝  Views(3523)  Comments(0Edit  收藏  举报