IOS Auto-Implement object serialization method

Source: Internet
Author: User

Object serialization in IOS requires compliance with the Nscoding protocol, and then archiving and assigning values to each property of an object, which is cumbersome to respond to. This paper mainly introduces the use of runtime traversal properties to greatly simplify the amount of code

The specific implementation code is as follows:
1. First establish the classification of NSObject, define the related types that may be used

StaticNSString *inttype =@"I";//int_32t (enum int type)StaticNSString *longtpye =@"L";//Long TypeStaticNSString *longlongtype=@"Q";//Longlong TypeStaticNSString *booltype =@"B";//BOOL TypeStaticNSString *floattype =@"F";//floatStaticNSString *doubletype =@"D";//DoubleStaticNSString *booltype =@"C";StaticNSString *stringtype =@"NSString";//nsstring TypeStaticNSString *numbertype =@"NSNumber";//NSNumber TypeStaticNSString *arraytype =@"arraytype";//Array TypeStaticNSString *imagetype =@"UIImage";//UIImage Type

It then facilitates its own property name in the archive method, and takes out the corresponding value of its own property and stores it locally. The Ivar Pointer (which defines an instance variable of the object, including the type and name) is traversed by the class property itself, with the following code

//Archive- (void) Encodewithcoder: (Nscoder *) acoder{unsignedintCount//Number of attributesIvar *vararray = Class_copyivarlist ([selfclass], &count);  for(inti =0; I < count; i++) {Ivar var=Vararray[i]; Const Char*cname = Ivar_getname (Var);//Property name C stringNSString *proname = [[NSString stringwithutf8string:cname] Substringfromindex:1];//OC String, and remove the underscore _        Const Char*ctype = Ivar_gettypeencoding (Var);//get variable type, c string        IDValue =[self valueforkey:proname]; NSString*protype = [NSString Stringwithutf8string:ctype];//OC String        if([Protype containsstring:@"NSString"]) {Protype=StringType; }        if([Protype containsstring:@"NSNumber"]) {Protype=Numbertype; }        if([Protype containsstring:@"Nsarray"]) {Protype=arraytype; }        if([Protype containsstring:@"UIImage"]) {Protype=ImageType; }        //(5). Encode by Type        if([Protype Isequaltostring:inttype] | | [Protype Isequaltostring:booltype] | |[Protype Isequaltostring:booltype])        {[Acoder encodeint32:[value intvalue] forkey:proname]; }        Else if([Protype Isequaltostring:longtpye]) {[Acoder encodeint64:[value longvalue] forkey:proname]; }        Else if([Protype Isequaltostring:floattype]) {[Acoder encodefloat:[value floatvalue] forkey:proname]; }        Else if([Protype Isequaltostring:longlongtype] | |[Protype Isequaltostring:doubletype])        {[Acoder encodedouble:[value doublevalue] forkey:proname]; }        Else if([Protype Isequaltostring:stringtype]) {//String Type[Acoder encodeobject:value forkey:proname]; }        Else if([Protype Isequaltostring:numbertype]) {[Acoder encodeobject:value forkey:proname]; }        Else if([Protype Isequaltostring:arraytype]) {[Acoder encodeobject:value forkey:proname]; }        Else if([Protype Isequaltostring:imagetype]) {//Image Type[Acoder encodedataobject:uiimagepngrepresentation (value)]; }} free (Vararray);}

Second, the solution, the principle and archive almost, directly on the code

-(Instancetype) Initwithcoder: (Nscoder *) adecoder{ Self=[self init]; if(self) {unsignedintcount; Ivar*vararray = Class_copyivarlist ([selfclass], &count);  for(inti =0; I < count; i++) {Ivar var=Vararray[i]; Const Char*cname = Ivar_getname (Var);//Property name C stringNSString *proname = [[NSString stringwithutf8string:cname] Substringfromindex:1];//OC String, and remove the underscore _            Const Char*ctype = Ivar_gettypeencoding (Var);//get variable type, c stringNSString *protype = [NSString Stringwithutf8string:ctype];//OC String            if([Protype containsstring:@"NSString"]) {Protype=StringType; }            if([Protype containsstring:@"NSNumber"]) {Protype=Numbertype; }            if([Protype containsstring:@"Nsarray"]) {Protype=arraytype; }            if([Protype containsstring:@"UIImage"]) {Protype=ImageType; }            if([Protype Isequaltostring:inttype] | | [Protype Isequaltostring:booltype] | |[Protype Isequaltostring:booltype]) {int32_t number=[Adecoder Decodeint32forkey:proname];            [Self setvalue:@ (number) forkey:proname]; }            Else if([Protype Isequaltostring:longtpye]) {int64_t number=[Adecoder Decodeint64forkey:proname];            [Self setvalue:@ (number) forkey:proname]; }            Else if([Protype Isequaltostring:floattype]) {floatNumber =[Adecoder Decodefloatforkey:proname];            [Self setvalue:@ (number) forkey:proname]; }            Else if([Protype Isequaltostring:longlongtype] | |[Protype Isequaltostring:doubletype]) {                DoubleNumber =[Adecoder Decodefloatforkey:proname];            [Self setvalue:@ (number) forkey:proname]; }            Else if([Protype Isequaltostring:stringtype]) {//String TypeNSString *string=[Adecoder Decodeobjectforkey:proname]; [Self SetValue:stringForkey:proname]; }            Else if([Protype Isequaltostring:numbertype]) {nsstring*number =[Adecoder Decodeobjectforkey:proname];            [Self setvalue:number forkey:proname]; }            Else if([Protype Isequaltostring:arraytype]) {Nsarray*array =[Adecoder Decodeobjectforkey:proname];            [Self Setvalue:array forkey:proname]; }            Else if([Protype Isequaltostring:imagetype]) {//Image TypeUIImage *image =[UIImage Imagewithdata:[adecoder decodedataobject];            [Self setvalue:image forkey:proname]; }        }    }    returnSelf ;}

The last is how to store the method, clear the stored local cache, and get the local storage data.

//Storage Path-(NSString *) filepathwithuniqueflagstring: (NSString *) uniqueflag{NSString*docpath =[Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastobject]; NSString*detailpath = [NSString stringWithFormat:@"%@_%@", uniqueflag,[nsstring stringwithutf8string:object_getclassname (self)]; NSString*path =[DocPath Stringbyappendingpathcomponent:detailpath]; returnpath;}//Save Object data to local- (void) Savedatatolocalwithuniqueflagkey: (NSString *) uniqueflagkey{[nskeyedarchiver archiverootobject:self tofile:[self filepathwithuniqueflagstring: Uniqueflagkey]];}//emptying the locally stored object data- (ID) Getdatafromlocalwithuniqueflagkey: (NSString *) uniqueflagkey{return[Nskeyedunarchiver unarchiveobjectwithfile:[self filepathwithuniqueflagstring:uniqueflagkey];}//get Object data from local-(BOOL) Removedatafromlocalwithuniqueflagkey: (NSString *) uniqueflagkey{Nserror*error =Nil; [[Nsfilemanager Defaultmanager] removeitematpath:[self Filepathwithuniqueflagstring:uniqueflagkey] Error:&ERROR]; if(!error) {        returnYES; }    Else {        returnNO; }}

The complete project is as follows: Https://github.com/maxzhang123/MXCoding.git

Reprint please indicate the source, thank you

IOS Auto-Implement object serialization method

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.