用Xcode建立Static Library重複利用你的程序代碼(即.a靜態庫)

參考:http://www.it165.net/pro/html/201302/4913.html

參考2:http://blog.csdn.net/fkuewfnh/article/details/35273415

在進行開發時,最常遇到的就是相同的功能,會在不同的地方用到。

用 .Net 開發的話,就會將程序包裝成 dll,直接在要使用的項目上加入參考即可。
在開發 iOS 其實也是有方法可以做到的
下面的步驟,會先建立一個 Cocoa Touch Static Library 的項目建立 Static Library,然後再建立一個 Single View Application 的項目來使用建立好的 Library 來進行測試
 
步驟如下:
一、建立 Cocoa Touch Static Library 項目
1. 開啓 Xcode ,選擇 Framework & Library,建立一個 Cocoa Touch Static LIbrary 項目,名稱爲「MyLibrary01」
 
\
 

2. 項目建立完成後,會看到 Xcode 有自動建立「MyLibrary01.h」、「MyLibrary01.m」,直接就實作這兩個檔案來測試吧。

 

\
 

3. 爲了測試用,簡單新增個 sayHello 單純輸出字符串的 Function

兩個檔案程序代碼如下:

MyLibrary01.h

 

01.//  MyLibrary01.h
02. 
03.//  MyLibrary01
04. 
05.//
06. 
07.//  Created by alanjiang on 13/2/25.
08. 
09.//  Copyright (c) 2013年 lab. All rights reserved.
10. 
11.//
12. 
13.#import<foundation foundation.h="">
14. 
15.@interfaceMyLibrary01 : NSObject
16. 
17.-(NSString *) sayHello;
18. 
19.@end</foundation>

MyLibrary01.m


01.//
02. 
03.//  MyLibrary01.m
04. 
05.//  MyLibrary01
06. 
07.//
08. 
09.//  Created by alanjiang on 13/2/25.
10. 
11.//  Copyright (c) 2013年 lab. All rights reserved.
12. 
13.//
14. 
15.#import"MyLibrary01.h"
16. 
17.@implementationMyLibrary01
18. 
19.-(NSString *) sayHello
20. 
21.{
22. 
23.return@"Hello 我是從 MyLibrary01 來的!!";
24. 
25.}
26. 
27.@end

4. 撰寫完成後,進行編譯,編譯的時候,不要選擇到「iOS Device」、要選擇 iPhone 或是 iPad,否則在使用此 Library 的項目在編譯時,會出現下面的 warming 訊息:
ld: warning: ignoring file /Users/alanjiang/Desktop/程序/Lab/UseMyLibrary01/UseMyLibrary01/libMyLibrary01.a, file was built for archive which is not the architecture being linked (i386): /Users/alanjiang/Desktop/程序/Lab/UseMyLibrary01/UseMyLibrary01/libMyLibrary01.a

\
 

5. 這樣就完成了,要使用的話,只要把「MyLibrary01.h」、「libMyLibrary01.a」拉到項目就可以了

 

\
 

PS. libMyLibrary01.a 放置的路徑比較不好找,可以在檔案上面按鼠標右鍵,選擇「Show in Finder」就可以很快找到了。

 

\
 
二、建立 Single View Application 項目
1. 開啓 Xcode ,選擇 Application,建立一個 Single View Application 項目,名稱爲「UseMyLibrary01」
 
\
 

2. 把「MyLibrary01.h」、「libMyLibrary01.a」用 Finder 拉到專案中,MyLibrary01.h 不用勾選 Add to targets

 

\
 

3. 完成之後,在 ViewController.m 裏使用我們建立的 MyLibrary01 裏的 sayHello Function www.it165.net

    記得要 import "MyLibrary01.h" 喔

 

\
 

4. 執行仿真器,會看到 Output 窗口有 NSLog 輸出的訊息,就是 sayHello 輸出的訊息,搞定收工!!

 

\
 
結論:
用此方式雖然不用每次都要複製相同的程序代碼到不同的項目下,可是也是需要夾帶 .h 檔案到項目下,檔案一多,也不見得便利,
下次分享製作 Framework 的方式,就可以解決此缺點。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章