Static Libraries with XCode and iPhone SDK

One of the easiest ways to overwhelm yourself when developing for iPhone OS is trying the all-in-one approach to code management. I’ve done it countless times and rooting through a maze of groups and files in a project can drive you insane. After frustration push me to the edge one too many times I finally snapped and sat down to figure out a better way.

When you have a large project, there’s often a lot of code that is very generic—an XML parser, network connection manager, location manager—that could be placed in their own shared libraries to use across different projects. This separation of code vastly increases the cleanliness of each individual project but also has other advantages including:

  • Clear boundaries for business logic, api requirements, and unit testing.
  • Less overlap in a single project when multiple developers are working together.

Moving the code to a library also removes it from the project with the “business logic”, allowing you to focus on the task at hand and prevent you from “tweaking” libraries just to accommodate the business logic of one particular project.

The iPhone SDK doesn’t support custom frameworks or dynamic libraries so you may not have thought it was possible but iPhone OS does does support static libraries and therefore allows you to write re-useable code—with a few caveats. This is how libraries such as Flurry or Google Mobile Analytics work.

The only disadvantage is that if you include other frameworks or libraries in your library you still need to include them ALL in your final project. Adding MapKit to a static library means you also need to add MapKit directly to the main project (which is why you need to add the SQL lib with Google analytics).

Creating your own library requires a few steps but it boils down to:

  1. Create an XCode project to contain all the code for a specific library.
  2. Create a static library target with the appropriate configuration.
  3. Create a project that will use the library.
  4. Import your static library project into your main project.
  5. Link in the static library.

To simplify steps one and two even further, I’ve created an iPhone OS Static Library Project template for XCode. Download it and feel free to suggest any changes you’d like to see.

Usage instructions and a quick “How To” are available on the project page.