組件化組件靜態(tài)庫動態(tài)庫加載xib資源的區(qū)別

動態(tài)庫形式:.dylib和.framework
靜態(tài)庫形式:.a和.framework
舉例demo:demoStatic


動態(tài)庫和靜態(tài)庫的區(qū)別

1、動態(tài)庫情況xib資源存在路徑

iOS在組件化過程中,一般來說,會把組件做成動態(tài)庫的形式,也就是使用use_frameworks!

圖1
這種情況下,無論你的xib放到Assets資源文件夾下還是Classes代碼文件夾下,系統(tǒng)都可以通過該組件的framework找到,如下圖
圖2

那么app運行起來之后,當app需要加載xib資源,會從demoStatic.framework這個動態(tài)庫中尋找,如果xib資源放在了Assets文件夾下,那么系統(tǒng)應(yīng)該從demoStatic.bundle里面找xib資源;如果xib資源放在了Classes文件夾下,那么系統(tǒng)應(yīng)該直接從demoStatic.framework里面找(即demoStatic.bundle同級目錄)。
下圖為demoStatic_Example.app的包內(nèi)容(靜態(tài)庫和動態(tài)庫兩種情況,此時的xib資源都在Assets文件夾下,所以xib的資源都應(yīng)該在demoStatic.bundle里面找,只是不同情況demoStatic.bundle的位置不同)
圖3|動態(tài)庫|Assets

圖3|靜態(tài)庫|Assets

圖3|動態(tài)庫|Classes
但是如果在podspec文件中聲明s.static_framework = true,如下圖
圖4
說明demoStatic組件允許打包成靜態(tài)庫,這樣的話,demoStatic_Example.app包內(nèi)容的Frameworks路徑下就沒有demoStatic.framework,所以這種情況下,必須把xib資源放到Assets文件夾下(參考圖3|靜態(tài)庫)[因為靜態(tài)庫的組件中,它的bundle路徑在demoStatic_Example.app下]。為了和圖片資源區(qū)分清楚,盡量在podSpec文件下指明路徑,參考圖4的s.source_bundles
下面我寫了一個加載Assets文件夾下xib資源的方法

#import "NSBundle+Xib.h"

@implementation NSBundle (Xib)
///這是NSBundle的Category
/// 如果xib文件放到了Assets文件夾下使用這個方法獲取xib所在bundle(兼容靜態(tài)庫和動態(tài)庫)
/// @param bundleName bundle名稱
+ (instancetype)yl_xibWithBundle:(NSString *)bundleName {
        
        
    if ([bundleName containsString:@".bundle"]) {
        bundleName = [bundleName componentsSeparatedByString:@".bundle"].firstObject;
    }
    NSBundle *lastBundle = nil;
    //沒使用framwork的情況下(靜態(tài)庫)
    NSURL *associateBundleURL = [[NSBundle mainBundle] URLForResource:bundleName withExtension:@"bundle"];
    
    //使用framework形式(動態(tài)庫)
    if (!associateBundleURL) {
        associateBundleURL = [[NSBundle mainBundle] URLForResource:@"Frameworks" withExtension:nil];
        associateBundleURL = [associateBundleURL URLByAppendingPathComponent:bundleName];
        associateBundleURL = [associateBundleURL URLByAppendingPathExtension:@"framework"];
        associateBundleURL = [associateBundleURL URLByAppendingPathComponent:bundleName];
        associateBundleURL = [associateBundleURL URLByAppendingPathExtension:@"bundle"];
        
    }
    
    lastBundle = [NSBundle bundleWithURL:associateBundleURL];
    
    return lastBundle;

}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容