在进行开发时,最常遇到的就是相同的功能,会在不同的地方用到。
用 .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
// MyLibrary01.h // MyLibrary01 // // Created by alanjiang on 13/2/25. // Copyright (c) 2013年 lab. All rights reserved. // #import @interface MyLibrary01 : NSObject -(NSString *) sayHello; @end
MyLibrary01.m
// // MyLibrary01.m // MyLibrary01 // // Created by alanjiang on 13/2/25. // Copyright (c) 2013年 lab. All rights reserved. // #import "MyLibrary01.h" @implementation MyLibrary01 -(NSString *) sayHello { return@"Hello 我是從 MyLibrary01 來的!!"; } @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」就可以很快找到了。

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 的方式,就可以解决此缺点。
出处:http://www.dotblogs.com.tw/alanjiang/archive/2013/02/26/93251.aspx