Protobuf of iOS network communication

Source: Internet
Author: User
Tags automake

Abstract when communicating on different platforms, the object needs to be serialized first. We use ' nskeyedarchiver ' for archiving on the iOS platform, and of course we can use data processing in JSON or XML format. ' Nskeyedarchiver ' is only available on the Ios/mac platform, so its archived binary data is not suitable for use between different platforms. JSON and XML, although easy to maintain, easy to read and widely used, but the use of data efficiency is not high. Google proposed Protocol buffers as a cross-platform, language-independent serialized data format. Protocol buffers provides code generation tools that enable you to generate code in different languages based on a defined data format and then integrate it into your project. Protocol Buffe ...

Protobuf iOS development of serialized data transfer

Catalogue [-]

    • Introduced
    • Preparatory work
    • Use protocol buffers in iOS
    • Summarize
Introduced

When communicating on different platforms, you first need to serialize the objects. We use archiving on the iOS platform NSKeyedArchiver , and of course we can use the data in JSON or XML format. NSKeyedArchivercan only be used on the Ios/mac platform, so its archived binary data is not suitable for use between different platforms. JSON and XML, although easy to maintain, easy to read and widely used, but the use of data efficiency is not high. Google proposed Protocol buffers as a cross-platform, language-independent serialized data format. Protocol buffers provides code generation tools that enable you to generate code in different languages based on a defined data format and then integrate it into your project. Protocol buffers currently has two forms: Proto2 and Proto3. Protocol buffers supports the generation of Java, Python, C + +, objective-c and other code.

Preparatory work
    1. Download protocol buffers Source code (), you can also download to the official website.

    2. Compile protocol buffers. Although we can directly bring its code or project into Xcode, we still need to compile the important Code generation tool (Protoc). Because protocol buffers compiles with UNIX tools such as Autoconf/automake/libtool, the Mac may not have its own, and it needs to be installed manually. We can install it using homebrew or macport ( Two is the right choice).

      • To install using HomeBrew :
      $ brew install autoconf$ brew install automake$ brew install libtool
      • To install using macport :
      $ sudo port install autoconf automake libtool

Readme.md says it can be ./configure configured and run directly, but the actual one step is to run the ./autogen.sh script, otherwise an error will occur. Unfortunately, autogen.sh will download https://googlemock.googlecode.com/files/gmock-1.7.0.zip. Gmock is outside the wall , can only use a ladder to get out (no ladder can find Camp David Education Exchange Group free of charge, will be invited to tea AH).

There are no scenarios for running autogen.sh:

2215: syntax error near unexpected token ‘enable‘$ ./configure: line 2215: ‘AM_MAINTAINER_MODE(enable)‘

Once the VPN is turned on, run the following script:

$ ./autogen.sh$ ./configure$ make# 如果希望安装protoc,执行下面的命令$ make install
Use protocol buffers in iOS
    1. Create the proto file to specify the data format, you can choose the Proto2 and Proto3 format, they have some subtle differences, in the generation of code will be prompted when the case to see the document language guide Proto3. The following uses the PROTO3 format and is saved as Person.proto.
Syntax ="Proto3";Message Person{String name =1;Int32 uid =2;string email =3;Enum phonetype { Span class= "hljs-constant" > MOBILE = 0; HOME = 1; Work = 2;} message  PhoneNumber  {string number = 1; Phonetype type = 2;} repeated phonenumber phone = 4;}       
    1. Use the protoc tool to generate the OBJECTIVE-C code. --proto_path=This is followed by the folder where the proto file needs to be processed, indicating that the --objc_out= generated objective-c code and the destination file storage path, and finally the file to be processed.
$ protoc --proto_path=. --objc_out=. Person.proto$ lsPerson.pbobjc.h    Person.pbobjc.m    Person.proto

After processing is complete, two files are generated, namely person.pbobjc.h and person.pbobjc.m . These two files are manual reference counts, so you need to set their compilation parameters after joining the project.

    1. For ease of management, we introduced the iOS Static Library project in protocol buffers directly. Of course, if you like to use C + +, you can directly import C + + code into the project, remember to set the header search Paths or User header search Paths .

Set up dependencies and connection libraries.

    1. Introduce a header file to start using.
#import"GPBProtocolBuffers.h"#import"Person.pbobjc.h"-(void) Viewdidload {[Super Viewdidload]; Person *person = [[Person alloc] init]; Person.name = @ "Zhangsan"; Person@ "[email protected]"; Person.uid = 23; nsdata *data = [person data]; nsstring *path = @ "/users/apple/desktop/test.data"; [Data Writetofile:path atomically:yes]; nsdata *ldata = [nsdata Datawithcontentsoffile:path]; Person *p = [person parsefromdata:ldata error:nil]; nslog (@ "\nname:%@\nemail:%@\nuid:%d", p .name, P.email, P.uid);}   

The printing results are as follows:

2015-12-02 13:09:46.890 ProtobufDemo[34761:150533]name:Zhangsanemail:[email protected]uid:23
    1. Protocol buffer Efficiency test the efficiency we're talking about here is the space occupancy rate. A simple comparison with the JSON format also stores the following information:
name: Zhangsanemail: diveinedu@qq.comuid: 23

The data size with protocol buffers is 30 bytes. While the utility JSON is stored, although we turn the key into a byte, the following:

NSDictionary *dict = @{@"n":@"Zhangsan",                       @"e":@"[email protected]", @"u":@23};NSData *jd = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];NSLog(@"jd: %lu", jd.length);

The JSON data still takes up 46 bytes and is less efficient as readability increases. let alone the XML.

Summarize

If you want to get better readability, you can use text formats such as JSON and XML. But Protocol buffer is a good choice for data efficiency. The storage efficiency is high, and the readability and maintainability of the proto file are strong.

Protobuf of iOS network communication

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.