Last time we talked about how to compile proto files into Objective-C files, now let’s actually use them in a project! So create a new Xcode project, or use an existing one that will use these new files. Now add the files (in my case, StoryRequest.pb.h, StoryRequest.pb.m, StoryResponse.pb.h, StoryResponse.pb.m) to the project, and compile.
And Kaboom! A gazillion errors!
This is because we haven’t included the static library yet. So here is how you add it to the project. The same steps apply for any such static libraries, not just protocol buffers.
1) Add ProtobufLib’s ProtocolBuffers target as direct dependency
Let’s go back to the file that you downloaded from the Protocol Buffer for Objective-C page. After you opened it, you will see a folder called
objectivec. If you look into it, you will see familiar stuff, such as the info.plist, the xcodeproj file, and a
Classes folder. This is the Xcode project for the static library. I like to keep these projects in sibling folders with my own projects so they can all share it. So I copied it into the same parent folder as my project so they can be siblings. I renamed the folder ProtobufLib. You can place this folder wherever you want. Just set up the path accordingly.
Now you want to add ProtobufLib’s ProtocolBuffers target as direct dependency. This means that when you build your project, it will first build the ProtocolBuffers target (which generates libProtocolBuffers.a), so your project will have a static library to link to. You do this by first dragging ProtobufLib’s ProtocolBuffers.xcodeproj into your project (I like to put it under Frameworks to keep things organized). You will then select ProtocolBuffers.xcodeproj and check libProtocolBuffers.a to tell Xcode to build that target, not the other two (the command line test and unit test).
And finally, right click on your own target, select Get Info. Then under the General tab, click on the + to add ProtocolBuffers as direct dependency.
2) Tell Xcode where the headers are
Now, also under target info, but in the Build tab, you want to specify where the headers are. Make sure that your configuration is set to All Configurations. Well, you don’t have to, but then you would have to do this same thing once for debug and another time for distribution. Under Header Search Paths, add ../ProtobufLib since they are in a sibling folder, and check the recursive option. You can set the path to ../ProtobufLib/classes so it just goes straight to that folder. I decided to just let it search recursively in this case, since I don’t feel like specifying sub directories like classes or headers for every single library I link to.
And compile again. It shall build without error.
In the next post, we’ll talk about how to use protocol buffers for the iPhone client to communicate with the server.