IOS-Object archiving (storing objects in a file)

Source: Internet
Author: User

Defining an Object
Person *p = [[Person alloc] init];
P.name = @ "Jack";
P.age = 20;
P.height = 180.0;
P.address = @ "American";
File storage Path
NSString *path = @ "/users/lianfu/desktop/one.data";
Archive an Object
[Nskeyedarchiver archiverootobject:p Tofile:path];

The path to the read file
NSString *path = @ "/users/lianfu/desktop/one.data";
Read the objects in the file
Person *P2 = [Nskeyedunarchiver Unarchiveobjectwithfile:path];
NSLog (@ "%@,%@,%d,%f", P2.name, P2.address, P2.age, p2.height);

The person object needs to implement two methods (and Viewcontroller to follow protocol <NSCoding>)
-(void) Encodewithcoder: (Nscoder *) acoder{
[Acoder encodeobject:_name forkey:@ "name"];
[Acoder encodeint:_age forkey:@ "age"];
[Acoder encodeobject:_address forkey:@ "Address"];
[Acoder encodefloat:_height forkey:@ "height"];
}
-(ID) Initwithcoder: (Nscoder *) adecoder{
if (self = [super init]) {
_name = [Adecoder decodeobjectforkey:@ "name"];
_age = [Adecoder decodeintforkey:@ "age"];
_height = [Adecoder decodefloatforkey:@ "height"];
_address = [Adecoder decodeobjectforkey:@ "Address"];
}
return self;
}

IOS-Object archiving (storing objects in a file)

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.