此處說的可拆卸,意思就是業務App的工程是否導入這個framework都不影響編譯。若是業務導入了這個framework,就可使用其中功能,若是沒導入,也能編譯經過。git
在咱們開發項目的過程當中,會導入不少的三方庫,好比:會導入公司內部業務封裝的、微信、微博和支付寶等相關的framework等。在稍微複雜一點的業務中,以下圖:github
其中,A.framework和B.framework都是靜態庫,A.framework使用了B.framework中的方法,那麼,通常狀況下在APP中想要使用A.framework中的方法,必需要同時將A.framework和B.framework導入到APP工程中,不然編譯時會報錯。可是在現實狀況中,可能業務不須要A包中涉及到B包的功能,所以只想導入A.framework且不想導入B.framework。objective-c
咱們新建了一個下面的工程,工程中有兩個framework,示例中APP直接使用TestDynamicSdk的方法,TestDynamicSdk使用TestStaticSdk的方法。微信
如下代碼工做在TestDynamicSdk中,咱們以TestDynamicSdk做爲上述A.framework的角色作說明:函數
#import "TestDynamicSdk.h"
//// __has_include() 宏在導入三方庫 .h 過程當中的使用
#if __has_include(<TestStaticSdk/TestStaticSdk.h>)
#import <TestStaticSdk/TestStaticSdk.h>
#ifndef HAS_IMPORT_DY
#define HAS_IMPORT_DY 1
#endif
#else
#ifndef HAS_IMPORT_DY
#define HAS_IMPORT_DY 0
#endif
#endif
@implementation TestDynamicSdk
//// 👆上面定義的宏HAS_IMPORT_DY的使用
- (NSString *)getCombineStrWithA:(NSString *)aStr B:(NSString *)bStr {
#if HAS_IMPORT_DY == 1
TestStaticSdk *staticSdk = [[TestStaticSdk alloc] init];
NSString *combinedStr = [staticSdk getCombineStrWithA:@"common_A_String" B:@"common_B_String"];
return combinedStr;
#else
return nil;
#endif
}
@end
複製代碼
這樣APP便可在使用TestDynamicSdk時自由拆卸TestStaticSdk.framework。工具
#import "TestDynamicSdk.h"
@interface TestDynamicSdk ()
@property (nonatomic, strong) id staticSdkObject;
@end
@implementation TestDynamicSdk
- (id)init {
self = [super init];
if (self) {
Class class = NSClassFromString(@"TestStaticSdk");
if (!class) {
NSLog(@"TestStaticSdk沒有編譯");
return self;
}
SEL sel = NSSelectorFromString(@"new");
id (*imp)(id, SEL) = (id (*)(id, SEL))[class methodForSelector:sel];
self.staticSdkObject = imp(class, sel);
}
return self;
}
- (NSString *)getCombineStrWithA:(NSString *)aStr B:(NSString *)bStr {
if (!_staticSdkObject) {
NSLog(@"staticSdkObject爲空");
return nil;
}
SEL sel = NSSelectorFromString(@"getCombineStrWithA:B:");
if (![_staticSdkObject respondsToSelector:sel]) {
NSLog(@"getCombineStrWithA:B:方法沒有實現");
return nil;
}
NSString * (*imp)(id, SEL, NSString *, NSString *) = (NSString * (*)(id, SEL, NSString *, NSString *))[_staticSdkObject methodForSelector:sel];
NSString *combinedStr = imp(_staticSdkObject, sel, aStr, bStr);
return combinedStr;
}
@end
複製代碼
這樣也能實現APP在使用TestDynamicSdk時自由拆卸TestStaticSdk.framework。優化
注意:atom
GitHub源碼spa
小編微信:可加並拉入《QiShare技術交流羣》。
關注咱們的途徑有:
QiShare(簡書)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公衆號)
推薦文章:
自定義WKWebView顯示內容(一)
Swift 5.1 (6) - 函數
Swift 5.1 (5) - 控制流
Xcode11 新建工程中的SceneDelegate
iOS App啓動優化(二)—— 使用「Time Profiler」工具監控App的啓動耗時
iOS App啓動優化(一)—— 瞭解App的啓動流程
iOS WKWebView的基本使用
Swift 5.1 (4) - 集合類型
奇舞週刊