iOS:iOS為什么要用-all_load、-ObjC、-force_load


為了減少工作量復用部分代碼,於是乎我們開始選擇重構整個項目,把可以公用的代碼放在一起打包成一個靜態庫導入到其他的項目中使用。

介紹這部分內容的文章在網上很多,各位可以Baidu一下細看。

但是每次在加入靜態庫的時候都會在other linker flag里設置可能需要的三個值:-all_load、-force_load、-ObjC。
很奇怪為什么要這樣做,而且有的時候什么都不設置也不影響靜態庫的使用。
所有使用了這個靜態庫的項目都沒有出現任何的問題,即使不設置那兩個flag值。


關於-ObjC的:

Reference: 
This flag causes the linker to load every object file in the library that defines an Objective-C class or category. 
While this option will typically result in a larger executable (due to additional object code loaded into the application), 
it will allow the successful creation of effective Objective-C static libraries that contain categories on existing classes.

翻譯過來是:

引用

這個flag告訴鏈接器把庫中定義的Objective-C類和Category都加載進來。這樣編譯之后的app會變大(因為加載了其他的objc代碼進來)。
如果靜態庫中有類和category分類的話只有加入這個flag才行,也即需要添加的操作如下:

 

 

關於-all_load的

Reference:
IMPORTANT: For 64-bit and iPhone OS applications, there is a linker bug that prevents -ObjC from loading objects files from static libraries that contain only categories and no classes. 
The workaround is to use the -all_load or -force_load flags. -all_load forces the linker to load all object files from every archive it sees, even those without Objective-C code.
-force_load is available in Xcode 3.2 and later. It allows finer grain control of archive loading. Each -force_load option must be followed by a path to an archive,and every object file in that archive will be loaded.

翻譯如下:

引用:

不過在64位的Mac系統或者iOS系統下,鏈接器有一個bug,會導致只包含有類別的靜態庫無法使用-ObjC標志來加載文件。變通方法是使用-all_load 或者-force_load標志,它們的作用都是加載靜態庫中所有文件,不過all_load作用於所有的庫,而-force_load后面必須要指定具體的文件。

 

解釋:

這個flag是專門處理-ObjC的一個bug的。用了-ObjC以后,如果類庫中只有category分類但是沒有類的時候,這些category分類還是加載不進來。

變通方法就是加入-all_load或者-force-load。

 

-all_laod:會強制鏈接器把目標文件都加載進來,即使沒有objc代碼。

-force_load:在xcode3.2后可用,而且-force_load后面必須跟一個要加載的靜態庫的具體路徑。

 

最后總結一下:

-all_load就是會加載靜態庫文件中的所有成員,

-ObjC就是會加載靜態庫文件中實現一個類或者分類的所有成員,

-force_load(包的路徑)就是會加載指定路徑的靜態庫文件中的所有成員。

所以對於使用runtime時候的反射調用的方法應該使用這三個中的一個進行link,以保證所有的類都可以加載到內存中供程序動態調用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM