ios 蓝牙项目中使用 Protocol Buffers

2016-02-01  本文已影响0人  徐东吴彦祖

配置Protocol Buffers

安装homebrew

-配置

  1. 在终端输入
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  1. 安装automake,libtool,protobuf
brew install automake
brew install libtool
brew install protobuf
  1. protoc-gen-obj 插件能将.proto文件编译成.h .m文件
git clone git@github.com:alexeyxo/protobuf-objc.git

cd到protobuf-objc

./autogen.sh
./configure
make
make install

最终生成的插件名字为protoc-gen-objc,会被安装到/usr/local/bin/目录下
在终端使用 touch test.proto创建一个proto文件
我用Xcode打开这个文件写入以下内容

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

proto的数据类型规则参考

protoc tes.proto --objc_out="."

最终会生成
test.pb.h
test.pb.m
到此说明ProtocoBuffer可以正常工作了。

项目中使用 proto

  1. 使用cocoapods 在Podfile文件中写入
pod 'ProtocolBuffers', '1.9.2'

执行pod install

  1. 将之前生成的.h .m文件导入项目
    编译会报错
    .h文件中会找不到 GeneratedMessageProtocol
    直接注释掉
    .m文件中
[self.unknownFields storeInDictionary:dictionary];

也直接注释掉

#import "Test.pb.h"

.proto文件中 required的属性必须要填值 optional可选
-序列化
test文件中写了Person 所有会生成Person类

Person* person = [[[[[Person builder] setId:123]
                                    setName:@"Bob"]
                                   setEmail:@"bob@example.com"] build];
NSData* data = [person data]; 

-发序列化

NSData* raw_data = ...;
Person* person = [Person parseFromData:raw_data];

proto就相当于将蓝牙设备传输过来的数据包解析成oc对象的方式 就跟项目中将json数据转oc对象类似。

上一篇 下一篇

猜你喜欢

热点阅读