Implementation of serialization and deserialization

Source: Internet
Author: User

Steps:

1. The object needs to support serialization and deserialization must follow the Nscoding protocol

2, the realization of nscoding in the method

3, respectively, using Nskeyedarchiver and Nskeyedunarchiver class

For serialization and deserialization

#import <Foundation/Foundation.h>

#import "DSObject.h"

int main (int argc, const char * argv[]) {

Dsobject *srcobj = [[Dsobject alloc] init];

Srcobj.name = @ "Zhang San";

Srcobj.age = 32;

Srcobj.childnames = @[@ "Xiao Zhang 31", @ "Xiao Zhang 32", @ "Xiao Zhang 33";

NSLog (@ "%@", srcobj);

Serialization (there is a direct way to save to a file, or it can be saved to a file via NSData)

NSData *data = [Nskeyedarchiver archiveddatawithrootobject:srcobj];

[Data writetofile:@ "/users/ds/desktop/1.txt" atomically:yes];

Deserialization

NSData *data1 = [NSData datawithcontentsoffile:@ "/users/ds/desktop/1.txt"];

Dsobject *desobj = [Nskeyedunarchiver unarchiveobjectwithdata:data1];

NSLog (@ "%@", desobj);

[Srcobj release];

return 0;

}

Encoding (for serialization)

-(void) Encodewithcoder: (Nscoder *) Acoder {

[Acoder encodeobject:_name forkey:@ "name"];

[Acoder encodeinteger:_age forkey:@ "age"];

[Acoder encodeobject:_childnames forkey:@ "Childnames"];

}

Decoding (for deserialization)

-(ID) Initwithcoder: (Nscoder *) Adecoder {

if (self = [self init]) {

_name = [Adecoder decodeobjectforkey:@ "name"];

_age = [Adecoder decodeintegerforkey:@ "age"];

_childnames = [Adecoder decodeobjectforkey:@ "Childnames"];

[_name copy];

[_childnames retain];

}

return self;

}

Implementation of serialization and deserialization

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.