iOS pb编译器使用

来源:互联网 发布:网络主播传媒公司 编辑:程序博客网 时间:2024/05/16 13:47

Protocol Buffers 是 Google 出品的用来序列化/反序列化数据的工具。原生支持 C++、Java、Python。

如果要在 iOS 上使用 PB,可以直接使用 C++,但是编译过程很麻烦,因此这里使用的是第三方的库。

安装 Protocol Buffers

  • 安装 homebrew
1
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  • 安装 automake、libtool、protobuf。这里安装的 protobuf 是 google 官方版本。
123
brew install automakebrew install libtoolbrew install protobuf

如果后面的步骤出错了,请确保已经安装了这些工具:automake、autoconf、autoreconf、aclocal、libtool、protoc。其中的 protoc 用来把 .proto 文件编译成 C++、Java 或 Python 代码。

  • 编译 protoc-gen-objc。protoc-gen-objc 是 protoc 的一个插件,使其能将 .proto 文件编译成 objective-c 代码。

12345678910111213
git clone git@github.com:alexeyxo/protobuf-objc.gitcd protobuf-objc./autogen.sh# 后面的参数保证 configure 能找到 protobuf 相关的头文件和库# 避免报 protobuf headers are required 错误./configure CXXFLAGS=-I/usr/local/include LDFLAGS=-L/usr/local/libmakemake install
如果出现以下错误

  • 利用 protoc 将 .proto 文件编译成 objective-c 代码。
1
protoc message.proto --objc_out="."

如果出现下面的错误:

12
protoc-gen-objc: program not found or is not executable--objc_out: protoc-gen-objc: Plugin failed with status code 1.

可以尝试:

1
cp /PATH/TO/protobuf-objc/src/compiler/protoc-gen-objc /usr/local/bin
  • 在 Podfile 中添加pod 'ProtocolBuffers', '1.9.2'然后执行pod install

  • 将生成的 .h 和 .m 文件添加到工程中,编译。

这里会提示找不到GeneratedMessageProtocol。你只需要帅气地将其注释掉就行了。

使用

假设有 person.proto 定义如下 

12345
message Person {  required int32 id = 1;  required string name = 2;  optional string email = 3;}

通过 protoc 生成 Person.pb.h 和 Person.pb.m 两个文件。

  • 序列化
1234
Person* person = [[[[[Person builder] setId:123]                                    setName:@"Bob"]                                   setEmail:@"bob@example.com"] build];NSData* data = [person data];
  • 反序列化
12
NSData* raw_data = ...;Person* person = [Person parseFromData:raw_data];

参考

http://protobuf.axo.io/#objc
https://github.com/alexeyxo/protobuf-objc

0 0
原创粉丝点击