With runtime, no matter how many attributes the model has, it can be done with a few lines of code.
Assume that the person class has more than N attributes, but (write 3 of them here)
. h
#import <Foundation/Foundation.h>
@interface person:nsobject <nscoding>
@property (nonatomic, assign) int age ;
@property (nonatomic, assign) int height;
@property (nonatomic, copy) nsstring *name;
@end
. m
#import "Person.h"
#import <objc/runtime.h>
#import <objc/message.h>
@implementation Mjperson
-(void) Encodewithcoder: (nscoder *) Encoder
{
unsigned int count = 0;
Ivar *ivars = class_copyivarlist ([person class], &count);
For (int i = 0; i<count; i++) {
Remove the member variables corresponding to the I position
Ivar Ivar = ivars[i];
View member Variables
const Char *name = ivar_getname (Ivar);
// archive
nsstring *key = [nsstring stringwithutf8string:name];
id value = [self valueforkey:key];
[Encoder Encodeobject:value Forkey:key];
}
Free (ivars);
}
-(ID) Initwithcoder: (nscoder *) Decoder
{
if (self= [Super Init]) {
unsigned int count = 0;
Ivar *ivars = class_copyivarlist ([person class], &count);
For (int i = 0; i<count; i++) {
Remove the member variables corresponding to the I position
Ivar Ivar = ivars[i];
// View member variables
const Char *name = ivar_getname (Ivar);
// archive
nsstring *key = [nsstring stringwithutf8string:name];
id value = [decoder decodeobjectforkey:key];
// set to member variable body
[self setvalue:value Forkey:key];
}
Free (ivars);
}
return self;
}
@end
After this writing, regardless of the number of properties, runtime can complete the model properties of the archive and solution, is not very convenient.
Of course, you can also draw the code inside the. h and. m macro, so that later you want to implement the storage of complex objects only two lines of code can be done.
ios--archive through runtime, reverse archive