iOS development iterates through the properties of the model class and improves the use of runtime to assign values to the model class

Source: Internet
Author: User

1. To traverse the properties of the model class, you first have to go through the runtime to get the properties of the model class, and the value of all the properties of the output model is not like traversing a For loop with dictionary and array. The following method uses the runtime to obtain the property string for the model class and returns it as an array. The code is as follows:

First, get the entity properties of model

1. To traverse the properties of the model class, you first have to go through the runtime to get the properties of the model class, and the value of all the properties of the output model is not like traversing a For loop with dictionary and array. The following method uses the runtime to obtain the property string for the model class and returns it as an array. The code is as follows:

///gets the name of all properties of the current object, returned as an array by the runtime-(Nsarray *) allpropertynames{///Store all property namesNsmutablearray *allnames =[[Nsmutablearray alloc] init]; ///number of stored propertiesUnsignedintPropertycount =0; ///to get the properties of the current class through the runtimeobjc_property_t *propertys = Class_copypropertylist ([selfclass], &propertycount); //Put attributes in an array for(inti =0; i < Propertycount; i + +) { ///Take out the first propertyobjc_property_t property =Propertys[i]; Const Char* PropertyName =Property_getname (property); [Allnames addobject:[nsstring Stringwithutf8string:propertyname]; }  ///ReleaseFree (propertys); returnAllnames;} 

2. After obtaining the property method of the model class, you need to generate a Get method for the property string, we can execute the GET method to get the value of the Model property, and the method below is to get the getter method of the property based on the property string. The name of the getter method of the attribute in OC is the same as the name of the property, and the generated getter method is relatively simple, the code is as follows:

#pragma Mark--Creates a setter method of the string through a string and returns-(SEL) Creatgetterwithpropertyname: (NSString *) propertyname{< c2/>//return

Second, the Get method execution

The next thing to do is to execute the Getter method through the runtime, which requires the method's signature to execute the Getter method. The method needs to be called through the signature of the method when the method to be executed in the OC runtime needs to pass in parameters or need to receive the return value. The following code is to create the signature of the method, and then through the signature to get the called object, in the bottom of the observes callback call the above two methods in passing the signature of the method to get the value of the Model property, the specific code is as follows:

- (void) displaycurrentmodleproperty{//Gets the attribute name of the entity classNsarray *array =[self allpropertynames]; //Stitching ParametersNsmutablestring *resultstring =[[Nsmutablestring alloc] init];  for(inti =0; i < Array.count; i + +) {  //getting the Get methodSEL GetSel =[self creatgetterwithpropertyname:array[i]]; if([self Respondstoselector:getsel]) {//obtaining signatures for classes and methodsNsmethodsignature *signature =[self Methodsignatureforselector:getsel]; //get the calling object from the signatureNsinvocation *invocation =[Nsinvocation invocationwithmethodsignature:signature]; //Set the target[invocation settarget:self]; //Set Selector[invocation Setselector:getsel]; //receive the returned valueNSObject *__unsafe_unretained returnvalue =Nil; //called[invocation invoke]; //Receive return value[Invocation getreturnvalue:&ReturnValue]; [Resultstring AppendFormat:@"%@\n", returnvalue]; }} NSLog (@"%@", resultstring); } 

Execute the above method to enter the value of the property in the model, and then call the above method to output the model's property value after the model is assigned a value in the main function, the calling code looks like this:

Beautifulgirlmodel *beautifulgirl = [Beautifulgirlmodel modelwithdictionary:data];  [Beautifulgirl Displaycurrentmodleproperty];

The result of the operation is as follows, and the output below is the value of the property in model.

Third, the dictionary key and the model properties of different processing methods

Sometimes the dictionary key and model properties are different, so how to solve this problem? The simplest approach is to maintain a mapping relationship method in a specific entity class, in which we can obtain a corresponding mapping relationship.

#pragma The mapping of the Return property and Dictionary key-(nsdictionary*return

2. Modify our convenient initialization method, in the case of a mapped dictionary and without a mapped dictionary, the method is different, the code to facilitate the initialization method is as follows:

-(Instancetype) Initwithdictionary: (nsdictionary *=ifif ([self Propertymapdic] ==elsereturn

3. The next step is to implement a mapping relationship to invoke the method, this method is to convert the dictionary key into a dictionary with the name of the property by mapping the relationship, and then call the previous assignment method, the code is as follows:

#pragmaAssigns a value to the model's properties based on the mapping relationship-(void) Assgintopropertywithnomapdictionary: (Nsdictionary *) data{///get the mapping of the dictionary and model propertiesNsdictionary *propertymapdic =[self propertymapdic]; ///Convert to a dictionary of the same key and property, and then call the Assgintopropertywithdictionary methodNsarray*dickey =[Data AllKeys]; Nsmutabledictionary*tempdic =[[Nsmutabledictionary alloc] initWithCapacity:dicKey.count];  for(inti =0; i < Dickey.count; i + +) {NSString*key =Dickey[i]; [Tempdic Setobject:data[key] forkey:propertymapdic[key];  } [self assgintopropertywithdictionary:tempdic]; } 

4. Create a Badboymodel and override the Propertymapdic method, and give the mapping relationship in the Propertymapdic method and return the dictionary corresponding to the mapping.

#import " BaseModelObject.h "  @interface Badboymodel:basemodelobject   * * * * *boy4  ;  @end

(2) Rewrite the mapping method, the key of the mapping dictionary is the key to convert the dictionary, value is the property name of the corresponding model.

#import "BadBoyModel.h"  @implementationBadboymodel#pragmaReturns the mapping of properties and Dictionary keys-(nsdictionary *) propertymapdic{return@{@"keyBoy1":@"boy1", @"KeyBoy2":@"Boy2", @"KeyBoy3":@"Boy3", @"KeyBoy4":@"Boy4",}; }  @end 

5. Test in the main function

(1) Generate our numerical dictionary, the key of the dictionary is different from the property to be assigned the model, the following loop is to generate the data used by the test:

//A dictionary that generates DIC's key is not the same as the model's property. nsmutabledictionary*data1 =[[Nsmutabledictionary alloc] init]; //Create a dictionary for testing for(inti =1; I <=4; i + +) {NSString*key = [NSString stringWithFormat:@"keyboy%d", I]; NSString*value = [NSString stringWithFormat:@"I'm the first%d bad boy .", I]; [Data1 Setobject:value Forkey:key]; } 

(2) Instantiate the model and output the results, of course, the previous code is also available.

Badboymodel *badboymodel = [Badboymodel modelwithdictionary:data1];  

The results of the run output are as follows:

Today the blog is here, so far, the model base class the most basic method encapsulation is almost, according to the specific requirements can be added new methods

RELATED Links: iOS development iterates through the properties of the model class and improves the use of runtime to assign a value to the model class Jade desk

iOS development iterates through the properties of the model class and improves the use of runtime to assign values to the model class

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.