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);