Archive: is to encode the relationship between the object and its properties and other objects, forming a document that can be stored either in the file system or between processes or networks.
The archive process saves the object graph as an architecture-independent byte stream, preserving the identity of the object and the relationship between the objects.
Objects that can be archived must comply with the Nscoding protocol to implement the following methods:
-(void) Encodewithcoder: (Nscoder *) acoder;-(ID) Initwithcoder: (Nscoder *) Adecoder;
Use the Nscoder object for encoding and decoding operations. Nscoder itself is an abstract class, which uses two specific classes, nskeyedarchiver and nskeyedunarchiver, that are actually running, that is, using key-based archiving techniques.
Archiving:
+ (BOOL) Archiverootobject: (ID) rootobject tofile: (NSString *) path;
Unarchiving:
+ (ID) unarchiveobjectwithfile: (NSString *) path;
Example:
//// nimoperson.h// testdemo/// / created by fu zheng on 15/8/13.// copyright (c) 2015 fuzheng. all rights reserved.//#import <foundation/foundation.h>@ Interface nimoperson : nsobject <nscoding> @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *gender; @property ( nonatomic, assign) NSUInteger age; @property (nonatomic, retain) nsset * Friends, @property (nonatomic, getter = ismarried) BOOL married; @end
nimoperson.m// testdemo//// created by fu zheng on 15/8/13.// Copyright (c) 2015 year fuzheng. all rights reserved.//# import "NimoPerson.h" @implementation NimoPerson- (void) Encodewithcoder: (nscoder *) acoder{ [acoder encodeobject:self.name forkey:@ "Name"]; [ acoder encodeobject:self.gender forkey:@ "Gender"]; [acoder encodeinteger : self.age forkey:@ "Age"]; [acoder encodeobject:self.friends forkey:@ " Friends "]; [acoder encodebool:[self ismarried] forkey:@" married "]; }- (ID) Initwithcoder: (nscoder *) adecoder{ if (self = [super init]) { _name = [[ Adecoder decodeobjectforkey:@ "Name"] copy]; _gender = [[adecoder decodeobjectforkey:@ "Gender"] copy]; _age = [ adecoder decodeintegerforkey:@ "Age"]; _friends = [adecoder decodeobjectforkey:@ "Friends"]; _married = [adecoder decodeboolforkey:@ "Married"]; } return self;} - (ID) init{ nsset *friends = [[nsset alloc] initwitharray : @[@ "Tom", @ "Jessica", @ "Lily"]]; return [self initwithname:@ "Tony" gender:@ "male" age:28 friends:friends married:no];} - (ID) initwithname: (nsstring *) name gender: (Nsstring *) Gender age :(Nsuinteger) Age friends: (NSSet *) Friends married: (BOOL) married{ if (Self = [super init]) { _name = [name copy]; _gender = [ name copy]; _age = age; _friends = friends; _married = married; } return self ;} - (nsstring *) description{ nsdictionary *desdic = @{@ "name": _ name, @ "Gender": _gender, @ "Age": [nsnumber numberwithinteger:_age], @ "Married": [nsnumber numberwithbool:_married ]}; return [nsstring stringwithformat:@ "%@", desdic];} @end
iOS Data Persistence---object archive