An Objective-C implementation of Google proto buffer for iOS. The orignal code comes from Booyah Inc. This implemenation add features to support write to / parse from delimited stream. This git repo also support cocoapods.
- iOS 4.0 and above
- Xcode 4 and above
- Support write to / parse from delimited stream (protobuf 2.3 feature).
You write a foo.proto
file like this:
message Person {
required int32 id = 1;
required string name = 2;
optional string email = 3;
}
Then you compile it with protoc
to produce code in Objective-C (see below).
Serialize to protobuf format:
Person* person = [[[[[Person builder] setId:123]
setName:@"Bob"]
setEmail:@"bob@example.com"] build];
NSData* data = [person data];
Unserialize from protobuf format data:
NSData* raw_data = ...;
Person* person = [Person parseFromData:raw_data];
Sometime is very useful to write multiple protobuf objects into a single file. This need use delimited format. Here is an example:
// serialize
NSOutputStream *ouputStream = [NSOutputStream outputStreamToFileAtPath:@"filename.dat" append:YES];
[ouputStream open];
for (int i=0; i<count; i++) {
// create a new Person object and assign value.
Person* person = ...;
// write to stream use delimited format
[person writeDelimitedToOutputStream:outputStream];
}
// unserialize
NSInputStream* inputStream = ...;
while(true) {
// read object one by one from stream.
Person* person = [Person parseDelimitedFromInputStream:inputStream];
if (!person) {
break;
}
....
....
}
If your project support cocoapods, add a line to your Podfile:
pod 'protobuf-ios'
Then update your dependences:
pod update
Drag protoc-ios.xcodeproj
to your Xcode project.
That's all.
Since the generated code is non-ARC, if your project use ARC by default,
you need add -fno-objc-arc
to generated files.
In Xcode, select the main project/targets/build phases/compile sources,
select the m files/double click under compiler flag/add -fno-objc-arc
to the popped window.
Run following command to compile and install the project.
$ cd compiler
$ ./autogen.sh
$ ./configure
$ make
$ make install (optional)
The compiler is genrated at src/protoc
.
Note:
You need autoconf
to compile from source code. If your system is not install autoconf, you can install it by brew:
$ brew install autoconf
If you system already install autoconf but linked, you can link it, here is an example:
$ brew install autoconf
Warning: autoconf-2.69 already installed, it's just not linked
$ brew link autoconf
Linking /usr/local/Cellar/autoconf/2.69... 28 symlinks created
To compile the proto definition to Objective-C, use following command:
./src/protoc --objc_out=. foo.proto
Contributions are welcome!
If you would like to contribute this project, please feel free to fork and send pull request.