什么是Bundle文件缺前?
簡單理解,就是資源文件包悬襟。我們將許多圖片诡延、XIB、文本文件組織在一起古胆,打包成一個(gè)Bundle文件。方便在其他項(xiàng)目中引用包內(nèi)的資源筛璧。
Bundle文件的特點(diǎn)逸绎?
Bundle是靜態(tài)的,也就是說夭谤,我們包含到包中的資源文件作為一個(gè)資源包是不參加項(xiàng)目編譯的棺牧。也就意味著,bundle包中不能包含可執(zhí)行的文件朗儒。它僅僅是作為資源颊乘,被解析成為特定的2進(jìn)制數(shù)據(jù)。
項(xiàng)目集成bundle
使用bundle就非常的easy了醉锄,將編譯好的XXXX.bundle 文件直接加入到需要的項(xiàng)目中乏悄。(拖進(jìn)去就??)省略了!
使用bundle中的資源
將要使用的bundle集成到項(xiàng)目中后恳不,就可以使用了檩小。需要注意的就是,bundle是靜態(tài)的烟勋,不進(jìn)行編譯的資源文件规求。所以,要使用bundle中的資源卵惦,就需要找到相應(yīng)的資源路徑阻肿。
VC獲得bundle中的資源
<pre>
NSString * bundlePath = [[ NSBundle mainBundle] pathForResource: @ "MyBundle"ofType :@ "bundle"];
NSBundle *resourceBundle = [NSBundle bundleWithPath:bundlePath];
UIViewController *vc = [[UIViewController alloc] initWithNibName:@"vc_name"bundle:resourceBundle];
</pre>
圖片獲得bundle中的資源
<pre>
UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
UIImage *image = [UIImageimageNamed:@"MyBundle.bundle/img_collect_success"];
[imgView setImage:image];
</pre>
或者
<pre>
UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
NSString *imgPath= [bundlePath stringByAppendingPathComponent:@"img_collect_success.png"];
UIImage *image_1=[UIImage imageWithContentsOfFile:imgPath];
[imgView setImage:image_1];
</pre>
當(dāng)然,可以寫成預(yù)編譯語句:
<pre>
define MYBUNDLE_NAME @ "MyBundle.bundle"
define MYBUNDLE_PATH [[[NSBundlemainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
define MYBUNDLE[NSBundle bundleWithPath: MYBUNDLE_PATH]
</pre>