在編寫第三方庫時, 如果需要用到一些圖片、聲音資源, 甚至是nib(xib), 就需要把這些資源打包成一個bundle. 一開始在其他第三方庫中看到bundle的時候, 覺得它好像是一個很高級的東西. 但是事實上, bundle就是一個普通得不能再普通的文件夾, 只是加上了.bundle
后綴, 一下子就高大上了起來.
加上.bundle
后綴的文件夾, 會被Mac識別為一個包. 將文件夾以包的形式存在, 可以當作一個整體方便地移動, 也可以讓別人不至于不小心改動到庫所依賴的資源.
步驟
將資源放到文件夾中, 重命名文件夾為
xxx.bundle
若bundle中有使用到xib文件, 需要使用命令把xib文件轉換為nib文件:
$ ibtool --errors --warnings --output-format human-readable-text --compile file.nib file.xib
*如果不轉換, 讀取的時候會導致如下錯誤:
Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle:
'NSBundle </var/mobile/Applications/C6718DB8-0C0F-4D38-84E6-55C145279957
/Documents/asset-4.bundle> (not yet loaded)' with name 'file''
- 把bundle拖進工程, 此時通過以下方法即可取到ZYBannerView.bundle
NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"bundle"]];