Creating a static library for the iPhone turned out to be a very simple. If you already have an Xcode project, you can easily add any portion of the source code in a static library.
Let’s learn step by step how:
- In your Xcode project, locate the “Targets” section under the “Groups & Files” sidebar. Right click on “Targets” and choose to add a new target, a Cocoa Touch “Static Library”.Give name to the library whatever you like.
- Now, Drag and drop existing files from your project list to compile sources section of static library. Remember, don’t add the .h files.
- Remove those same source code files from your application.
- Now, add the new static library to your target application via the “General” settings for the target:
- Add “-ObjC” to the “Other Linker Flags” in application’s target settings. It is not always necessary. This is only required if your static library defines Objective-C classes that your app is going to reference.
- Build your static library for all the SDK targets, simulator and iPhone Device.Build your app. It should now be referencing the static library rather than compiling from the original source code.
Now, we will learn how to do it Xcode 4.
- Select your project file in Xcode, and click on the Add Target button at the bottom of the Project Settings screen. Select the Cocoa Touch Static Library template from the Framework and Library section and click Next. Name it whatever you like.
- To use any of the classes in your static library you must link it to your main application target.
Select your main application target, then click on Build Phases and expand the Target Dependencies section. Click on the plus(+) button and select your static library from the list. This tells the linker to build your static library’s classes into your main target after compiling them.
- Select your main application target, then click on Build Phases and expand the Link Binaries with Libraries section. Click on the plus(+) button and select your static library from the list. This tells Xcode that when you build your main project, it needs to build the static library first.
- When you add code to the project, you will have the option of selecting in which target you want to add code. Add code in static library what you want.
- Then, build your project normally. Because you have setup a dependency between your main application target and the static library, your library is automatically compiled when required. Since you have multiple targets, you can also change your build target to the static library if you just want to build it stand alone for debugging.