
雖然 Objective C 的經驗不多,但漸漸地會想把一些共用的程式碼弄成 library 來使用,在加上 git 來管理,這時候就會想到 git submodule 的使用。原先以為把 xcode project 拖拉進來就可以了,後來發現這一切都只是幻想 XD 整體上的概念:編譯時要能找到(header search path),連結時要能找到(link binary)。原本以為拖拉其他 project 進來就能自動化搞動,最後發現還是要手動設定一些環境,所以就來筆記一下。
例如有 Base.xcodeproj 和 Test.xcodeproj,先把常用的程式碼都寫在 Base.xcodeproj:
建立 Xcode Project:

新增 TARGETS -> Add Target:

把想要編成 static library 的程式碼擺進 Compile Sources:


使用 git 管理(假設在 /tmp/base.git):
$ mkdir /tmp/base.git
$ cd /tmp/base.git
$ git init --bare
$ cd /path/Base
$ ls
Base Base.xcodeproj BaseLib
$ git init
Initialized empty Git repository in /path/Base/.git/
$ git remote add origin /tmp/base.git
$ git add .
$ git commit -am 'init'
$ git push origin master
在 Test.xcodeproj 裡使用 Base.xcodeproj:
建立 Test xcodeproj:

使用 git 管理(假設在 /tmp/test.git):
$ mkdir /tmp/test.git
$ cd /tmp/test.git
$ git init --bare
$ cd /path/Test
$ ls
Test Test.xcodeproj
$ git init
Initialized empty Git repository in /path/Test/.git/
$ git remote add origin /tmp/test.git
$ git add .
$ git commit -am 'init'
$ git push origin master
使用 git submodule 管理 Base library:
$ cd /path/Test
$ ls
Test Test.xcodeproj
$ git submodule add /tmp/base.git libbase
Cloning into 'libbase'...
done.
$ ls -a
. .git Test libbase
.. .gitmodules Test.xcodeproj
$ cat .gitmodules
[submodule "libbase"]
path = libbase
url = /tmp/base.git
$ git commit -am 'add libbase'
[master 5f69c71] add libbase
2 files changed, 4 insertions(+)
create mode 100644 .gitmodules
create mode 160000 libbase
$ git push origin master
設定 Text.xcodeproj:
拖拉 Base.xcodeproj 進來(從 /path/Test/libbase):

設定 Header Search (/path/Test/libbase):


設定 Other Linker Flags:
-all_load (如果 library 中有 categories)
設定 Link Binary With Libraries:

更新 git:
$ cd /path/Test
$ git add .
$ git commit -am 'add libbase'
$ git push origin master
如此一來,未來在取 Test 的時候,就可以這樣用:
$ git clone --recursive /tmp/test.git testxcode
Cloning into 'testxcode'...
done.
Submodule 'libbase' (/tmp/base.git) registered for path 'libbase'
Cloning into 'libbase'...
done.
Submodule path 'libbase': checked out '920380a7c727d7fb42e38e89bd2eac7a3d2ef72f'
$ ls -a testxcode
. .git Test libbase
.. .gitmodules Test.xcodeproj
此外,其他時候可能會需要以下指令:
$ git submodule update --init --recursive