framework是一種優秀的資源打包方式,咱們平時看到的第三方發佈的framework大部分都是靜態庫,蘋果對iOS容許使用動態庫,可是要利用動態庫熱更新,因爲蘋果的審覈和簽名技術,暫時仍是不行,內部使用仍是可行的git
# 頭文件部分
#import <Foundation/Foundation.h>
@interface DynamicLlib : NSObject
- (void)doSomething;
@end
# 實現部分
#import "DynamicLlib.h"
@implementation DynamicLlib
- (void)doSomething{
NSLog(@"doSomething!");
}
@end
複製代碼
2.1. 使用NSBundle加載動態庫github
- (IBAction)loadFrameWorkByBundle:(id)sender {
//從服務器去下載而且存入Documents下(只要知道存哪裏便可),事先要知道framework名字,而後去加載
NSString *frameworkPath = [NSString stringWithFormat:@"%@/Documents/DynamicLlib.framework",NSHomeDirectory()];
NSError *err = nil;
NSBundle *bundle = [NSBundle bundleWithPath:frameworkPath];
NSString *str = @"加載動態庫失敗!";
if ([bundle loadAndReturnError:&err]) {
NSLog(@"bundle load framework success.");
str = @"加載動態庫成功!";
} else {
NSLog(@"bundle load framework err:%@",err);
}
}
複製代碼
2.2. 使用dlopen加載動態庫bash
// 動態庫中真正的可執行代碼爲DynamicLlib.framework/DynamicLlib文件,所以使用dlopen時指定加載動態庫的路徑爲DynamicLlib.framework/DynamicLlib
NSString *documentsPath = [NSString stringWithFormat:@"%@/Documents/DynamicLlib.framework/DynamicLlib",NSHomeDirectory()];
[self dlopenLoadDylibWithPath:documentsPath];
if (dlopen([path cStringUsingEncoding:NSUTF8StringEncoding], RTLD_NOW) == NULL) {
char *error = dlerror();
NSLog(@"dlopen error: %s", error);
} else {
NSLog(@"dlopen load framework success.");
}
複製代碼
2.3. 調用動態庫中的方法服務器
//調用framework的方法,利用runtime運行時
- (IBAction)callMethodOfFrameWork:(id)sender {
Class DynamicLlibClass = NSClassFromString(@"DynamicLlib");
if(DynamicLlibClass){
//事先要知道有什麼方法在這個framework中
id object = [[DynamicLlibClass alloc] init];
//因爲沒有引入相關頭文件故經過performSelector調用
[object performSelector:@selector(doSomething)];
}else {
NSLog(@"調用方法失敗!");
}
}
複製代碼
附:個人博客地址app