When we archive custom objects, we can override the Encodewithcoder and Initwithcoder of the custom model.
That's probably the beginning, and when there's a lot of attributes, it doesn't seem like it's a good idea to repeat the same thing. Actually, we can give it to runtime.
-(void) Encodewithcoder: (Nscoder *) Acoder//encode attribute { [acoder encodeObject:self.name forkey:@ ' name ']; [Acoder encodeObject:self.phone forkey:@ "Phone"]; [Acoder encodeInteger:self.age forkey:@ "age"]; } -(ID) Initwithcoder: (Nscoder *) Adecoder//decode attribute { NSString *name1 = [adecoder decodeobjectforkey:@ "name"]; NSString *phone1 = [Adecoder decodeobjectforkey:@ "Phone"]; int age1 = [Adecoder decodeintegerforkey:@ "age"]; [Self initwithname:name1 phone:phone1 age:age1]; return self;}
Use runtime to achieve the above functions
-(void) Encodewithcoder: (Nscoder *) encoder{unsigned int count; Ivar *ivar = Class_copyivarlist ([User class], &count); for (int i=0; i<count; i++) {Ivar IV = Ivar[i]; const char *name = Ivar_getname (iv); NSString *strname = [NSString stringwithutf8string:name]; Use KVC to value id value = [self valueforkey:strname]; [Encoder Encodeobject:value Forkey:strname]; } free (Ivar);} -(ID) Initwithcoder: (Nscoder *) decoder{self = [super init]; if (self) {unsigned int count = 0; Gets the name of all member variables in the class Ivar *ivar = Class_copyivarlist ([User class], &count); for (int i = 0; i<count; i++) {Ivar IVA = ivar[i]; const char *name = Ivar_getname (IVA); NSString *strname = [NSString stringwithutf8string:name]; The value ID of the file to be extracted is = [decoder decodeobjectforkey:strname]; Use KVC to assign a value to a property [self setvalue:value forkey:strname]; } Free (Ivar); } return self;}
Use runtime to rewrite the coder and Decode methods when archiving the solution