In iOS, an instance object is stored in a sandbox, called an archive, and an instance object is read from a sandbox file called a solution file.
A chestnut is about to be born: for example, you want to deposit the value of the name and age attribute in a Zhhperson class into a sandbox file and read it in a sandbox file when needed.
Analysis:
In order to archive the object of the person class, the operation of the file must be implemented in two ways: Encodewithcoder: The system executes automatically when the file is archived, Initwithcoder: The system executes automatically when the document is unpacked.
For the implementation of the two methods, here is the use of the High: the runtime mechanism. This chestnut does not see the benefits of the runtime mechanism. But, but, finally, no, but.
ZHHPerson.h
#import <Foundation/Foundation.h>
@interface Person:nsobject
@property (nonatomic, copy) nsstring* name;
@property (nonatomic, assign) int age;
@end
Zhhperson.m
#import "ZHHPerson.h"
#import <objc/runtime.h>
@implementation Zhhperson
Solution file
-(ID) Initwithcoder: (Nscoder *) Decoder {
if (self = [super init]) {
U_int count;
Get all member variables of this class
ivar* Ivars = Class_copyivarlist ([self class], &count);
for (U_int i=0; i<count; i++) {
Remove the member variable of the corresponding position
Ivar Ivar = ivars[i];
Const char* KeyChar = Ivar_getname (Ivar);
Solution file
nsstring* keystr = [NSString Stringwithutf8string:keychar];
[Self Setvalue:[decoder decodeobjectforkey:keystr] forkey:keystr];
}
Free (ivars);
}
return self;
}
Archive
-(void) Encodewithcoder: (Nscoder *) encoder
{
unsigned int count = 0;
Get all member variables of this class
Ivar *ivars = Class_copyivarlist ([self class], &count);
Iterate through all the member variables
for (int i = 0; i<count; i++) {
Remove the member variable of the corresponding position
Ivar Ivar = ivars[i];
View member variables
const char *keychar = Ivar_getname (Ivar);
Archive
NSString *keystr = [NSString Stringwithutf8string:keychar];
[Encoder encodeobject:[self VALUEFORKEY:KEYSTR] forkey:keystr];
}
Release
Free (ivars);
}
Rewrite
-(nsstring*) Description {
return [NSString stringwithformat:@ "name =%@, age =%d", Self.name, Self.age];
}
@end
The Zhhperson class is okle.
Now you can use this class to do the file, archive the operation.
Archive:
zhhperson* p = [[Person alloc] init];
P.name = @ "Zhh";
P.age = 25;
[Nskeyedarchiver archiverootobject:p Tofile:path];
Solution file:
zhhperson* p = [Nskeyedunarchiver Unarchiveobjectwithfile:path];
NSLog (@ "%@", p);
iOS archive, solution files