6

What is the best way to reuse code within projects?

Let's say I implemented a UI Element and I want it to be used in both my iphone and ipad application without having to copy the code over and have 2 copies of it.

halfer
  • 19,824
  • 17
  • 99
  • 186
aryaxt
  • 76,198
  • 92
  • 293
  • 442

2 Answers2

5

Just create a project, which includes all your shared code in XCode and reference this project in your iPhone and iPad application project. Plain and simple.

Henrik P. Hessel
  • 36,243
  • 17
  • 80
  • 100
  • I hope it's as simple as you mentioned. Can you please explain how to reference a project within another? is it just dragging and dropping or is it in build setting? – aryaxt Jul 05 '11 at 18:34
  • 1
    Just drop the the shared project in your Groups & Files navigator window and uncheck "Copy Files". – Henrik P. Hessel Jul 05 '11 at 18:37
  • +1 to the comment and the answer. You may want to add it to the main answer. – Praveen S Jul 05 '11 at 19:21
  • I think this is a great method if you never have to change this code again. Otherwise this could be difficult. – dasdom Jul 05 '11 at 19:37
  • This doesn't work, my main project doesn't recognize the classes in my sub project. I tried to do #import "myFile.h" and I get "myFile.h not found" – aryaxt Jul 05 '11 at 21:40
2

For me I would make a static library project which contains the shared code (UI Element in your example) in Xcode.

Then when I need to use the library in the iPhone or iPad app project, then I can just reference the static library project by drag and drop the project to the Project Navigator and configure the correct dependency, library used and header search path. In this way you always have a single source of library source code for easier maintenance and modification.

Certainly you can actually compile the static library into binary and link it to your project, but it just not too flexible when you find bugs in your static library and need to switch to another project to correct the bug, and then do the compile and copy of the binary library file.

I have just wrote an article (link below) on how to link up the static library project to an iOS project on Xcode 4.3.2. This maybe useful for you to solve the header not found problem you encountered. Hope this help.

http://vicidi.wordpress.com/2012/04/11/linking-an-ios-static-library-project-in-another-project-in-xcode-4-3-2/

VCD
  • 889
  • 10
  • 27