Protocol Buffers 是 Google 出品的用来序列化/反序列化数据的工具。原生支持 C++、Java、Python。ios
若是要在 iOS 上使用 PB,能够直接使用 C++,可是编译过程很麻烦,所以这里使用的是第三方的库。c++
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install automake brew install libtool brew install protobuf
$ cd compiler $ ./autogen.sh $ ./configure $ make $ make install (optional)
git clone git@github.com:alexeyxo/protobuf-objc.git cd protobuf-objc ./autogen.sh # 后面的参数保证 configure 能找到 protobuf 相关的头文件和库 # 避免报 protobuf headers are required 错误 ./configure CXXFLAGS=-I/usr/local/include LDFLAGS=-L/usr/local/lib make make install
若make后编译不经过,报错以下:git
google/protobuf/message.cc:130:60: error: implicit instantiation of undefined template 'std::__1::basic_istream<char, std::__1::char_traits<char> >' return ParseFromZeroCopyStream(&zero_copy_input) && input->eof(); ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/iosfwd:109:33: note: template is declared here class _LIBCPP_TYPE_VIS_ONLY basic_istream; ^ google/protobuf/message.cc:135:67: error: implicit instantiation of undefined template 'std::__1::basic_istream<char, std::__1::char_traits<char> >' return ParsePartialFromZeroCopyStream(&zero_copy_input) && input->eof(); ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/iosfwd:109:33: note: template is declared here class _LIBCPP_TYPE_VIS_ONLY basic_istream; ^ google/protobuf/message.cc:175:16: error: implicit instantiation of undefined template 'std::__1::basic_ostream<char, std::__1::char_traits<char> >' return output->good(); ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/iosfwd:111:33: note: template is declared here class _LIBCPP_TYPE_VIS_ONLY basic_ostream; ^ 3 errors generated. make[2]: *** [message.lo] Error 1 make[1]: *** [all-recursive] Error 1 make: *** [all] Error 2
根据错误信息,对报错的文件进行以下修改:github
protobuf-2.4.1/src/google/protobuf/message.cc,添加#include<istream>objective-c
添加后make成功。make install,安装到自定义目录。ruby
这些完成以后,写一个protoc文件测试: UserInfo.protoapp
enum UserStatus { OFFLINE = 0; ONLINE = 1; } message UserInfo { required int64 acctID = 1; required string name = 2; required UserStatus status = 3; }
转换:curl
$protoc --objc_out=. UserInfo.proto
在当前目录出现两个文件: UserInfo.pb.h UserInfo.pb.m
工具
在 Podfile 中添加 pod 'ProtocolBuffers', '1.9.2'
而后执行 pod install
。测试
生成完成,使用起来很方便,导入framework静态库到工程中,使用方法:
UserInfoBuilder* builder = [UserInfo builder]; [builder setName:@"zhangsan"]; [builder setAcctId:1000]; [builder setStatus:UserStatusOnline]; UserInfo* info1 = [builder build]; NSData* data = info1.data; NSLog(@"data:%@", data); //data->obj UserInfo* info2 = [UserInfo parseFromData:data]; NSLog(@"obj:%@", info2);