Protobuf use on iOS

Source: Internet
Author: User

Camp David Education original articles, reproduced please indicate the source. Our dream is to do the best iOS development training!

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 (), can also be downloaded 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 Select a line ).

    • 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 said can be directly used ./configure is configured and compiled to run, but the actual one step is to run ./autogen.sh the script, otherwise an error will occur. Unfortunately, however, Https://googlemock.googlecode.com/files/gmock-1.7.0.zip is downloaded in autogen.sh. Gmock is in   outside the wall   You can only use a ladder to get it (no ladder to find   Camp David Education   Exchange Group for free, will you be invited to tea?).

There are no scenarios for running autogen.sh:

$./configure--with-protoc=protoc$./configure:line 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# If you want to install PROTOC, execute the following command $ 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 {     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.

650) this.width=650; "src=" Http://io.diveinedu.com/images/objc/protobuf_3.png "/>

    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 .

650) this.width=650; "src=" Http://io.diveinedu.com/images/objc/protobuf_1.png "/>

Set up dependencies and connection libraries.

650) this.width=650; "src=" Http://io.diveinedu.com/images/objc/protobuf_2.png "/>

    1. The

      introduces the 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 = @ "[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: [Email protected]uid: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.

Camp David Academy (Advanced Development Video): http://v.diveinedu.com

The club of Great concentration (iOS interview required): Http://divein.club

650) this.width=650; "src=" http://io.diveinedu.com/images/qrcode-diveinedu-mp-weixin.jpg "style=" width:200px; height:200px; "/>


Protobuf use on iOS

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.