美文网首页iOSiOS Developer程序员
Protobuf在Objective-C中的一次小实践

Protobuf在Objective-C中的一次小实践

作者: KFAaron | 来源:发表于2018-03-14 21:13 被阅读121次

    本篇文章完全是Protobuf在Objective-C中一次小实践的记录。

    环境搭建

    1、下载protobuf源码。
    git clone https://github.com/google/protobuf.git
    2、终端执行命令,安装proto编译器(如果一切顺利,没有报错,忽略步骤3~10)。
    objectivec/DevTools/full_mac_build.sh
    报如下错误:(如果没有此错误可以忽略步骤3)

    ./autogen.sh: line 50: autoreconf: command not found

    3、安装autoreconf。
    brew install automake
    报如下错误:(如果没有此错误可以忽略步骤4)

    Homebrew must be run under Ruby 2.3! You're running 2.0.0. (RuntimeError)

    4、升级ruby。
    brew install ruby@2.3
    报如下错误:(如果没有此错误可以忽略步骤5)

    Error: Xcode alone is not sufficient on Sierra.
    Install the Command Line Tools:
    xcode-select --install

    5、安装Command Line Tools。
    xcode-select --install
    6、重新升级ruby。
    brew install ruby@2.3
    7、重新安装autoreconf。
    brew install automake
    8、重新安装proto。
    objectivec/DevTools/full_mac_build.sh
    报如下错误:

    configure.ac:30: error: possibly undefined macro: AC_PROG_LIBTOOL
    If this token and others are legitimate, please use m4_pattern_allow.
    See the Autoconf documentation.
    autoreconf: /usr/local/Cellar/autoconf/2.69/bin/autoconf failed with exit status: 1

    9、安装libtool。
    brew install libtool
    10、重新安装proto。
    objectivec/DevTools/full_mac_build.sh

    测试准备

    1、把objectivec/*.h,objectivec/google/protobuf/*.pbobjc.h, objectivec/google/protobuf/*.pbobjc.m, and objectivec/*.m except for objectivec/GPBProtocolBuffers.m加入工程当中。
    如果工程使用ARC,为所有的.m文件关掉ARC(-fno-objc-arc)
    2、约定数据格式,先新建一个proto文件(如果与服务器通信,提前跟后台约定好数据格式,就像JSON格式数据一样提前约定好数据格式,不然无从解析)。
    vim KFATestPackage.KFATestMessage.proto
    根据约定的格式编辑proto文件:

    package KFATestPackage;
    
    message KFATestMessage {
        required string name = 1; // 姓名 必须
        required string sex  = 2; // 性别 必须
        optional string age  = 3; // 年龄 可选
    }
    

    3、把生成的KfatestPackageKfatestMessage.pbobjc.hKfatestPackageKfatestMessage.pbobjc.m文件加入工程中,并给KfatestPackageKfatestMessage.pbobjc.m文件关闭ARC模式(-fno-objc-arc)

    代码测试

    编写测试代码:

    // 序列化
        KFATestMessage *message = [KFATestMessage message];
        message.name = @"张三";
        message.sex = @"男";
        message.age = @"18";
        NSLog(@"%@--%@--%@",message.name,message.sex,message.age);
        NSData *messageData = message.data;
        
        // 反序列化
        KFATestMessage *rMessage = [KFATestMessage parseFromData:messageData error:NULL];
        NSLog(@"%@==%@==%@",rMessage.name,rMessage.sex,rMessage.age);
    
    编译,报如下错误:

    Compile Sources添加.m文件:

    重新编译,打印结果如下:

    ZSPlatformSDKDemo[91110:6237495] 张三--男--18
    2018-03-14 20:28:36.108678+0800
    ZSPlatformSDKDemo[91110:6237495] 张三==男==18

    本次只是一次简单的序列化和反序列化的小实践,还有更多的东西有待研究,比如proto文件的语法,比如自定义GPBMessage类的实现和使用以及更复杂的数据结构等等。

    参考链接

    相关文章

      网友评论

        本文标题:Protobuf在Objective-C中的一次小实践

        本文链接:https://www.haomeiwen.com/subject/wtyqqftx.html