IOS developer traverses the attributes of the Model class and uses Runtime to assign values to the Model class. iosmodel

Source: Internet
Author: User

IOS developer traverses the attributes of the Model class and uses Runtime to assign values to the Model class. iosmodel

In the previous blog "assign values to Model classes using Runtime for iOS development", we introduced how to assign values to attributes of object classes in the base classes of object classes during Runtime, the premise of this method is that the dictionary Key must be the same as the Property Name of the object class, and then the Setter method is generated and executed during the runtime to assign values to the attributes of the Model class.

The benefit of assigning values to Model class attributes through Runtime is that it facilitates code maintenance and improves development efficiency. When you get the parsed dictionary, you do not need to assign the dictionary value to the attributes of the corresponding Model class one by one through the key, this blog will show you how to traverse the attribute values in the Model and how to calculate negative values when the attribute names of the dictionary Key and Model are different.

Next, we will add Runtime in the Model base class based on the previous Blog Code to traverse the attribute values of the Model class.

1. Obtain the object attributes of the Model.

1. to traverse the attributes of the Model class, you must first use Runtime to obtain the attributes of the Model class. The values of all the attributes of the output Model are not handled in a for loop like traversing Dictionary and Array, the following method uses Runtime to obtain the attribute string of the Model class and return it as an array. The Code is as follows:

1 // obtain the names of all attributes of the current object through the runtime, and return 2-(NSArray *) as an array *) allPropertyNames {3 // store all attribute names 4 NSMutableArray * allNames = [[NSMutableArray alloc] init]; 5 6 // Number of stored attributes 7 unsigned int propertyCount = 0; 8 9 // obtain the attributes of the current class through runtime 10 objc_property_t * propertys = class_copyPropertyList ([self class], & propertyCount ); 11 12 // put the attribute in the array 13 for (int I = 0; I <propertyCount; I ++) {14 // retrieve the first attribute 15 objc_property_t property = propertys [I]; 16 17 const char * propertyName = property_getName (property); 18 19 [allNames addObject: [NSString stringwithuf8string: propertyName]; 20} 21 22 // Release 23 free (propertys); 24 25 return allNames; 26}

 

2. after obtaining the attribute methods of the Model class, we need to generate the get method for the attribute string. We can execute the get method to obtain the value of the Model attribute, the following method obtains the getter method of the Attribute Based on the attribute string. The getter method of the attribute in OC has the same name as the attribute name. The getter method is easy to generate. The Code is as follows:

1 # pragma mark -- use a string to create the Setter method of the string and return 2-(SEL) creatGetterWithPropertyName: (NSString *) propertyName {3 4 // 1. return get method: The get method in oc is the attribute itself 5 return NSSelectorFromString (propertyName); 6}

 

2. Get method execution

The next step is to use Runtime to execute the Getter method, which needs to be executed through the method signature. When you need to pass in a parameter or receive a return value for the method to be executed during OC running, you need to call the method through the method signature. The following code is used to create a method signature and obtain the called object through the signature. In the following code, call the above two methods to obtain the Model attribute value through the method signature, the Code is as follows:

1-(void) displayCurrentModleProperty {2 3 // obtain the object class attribute name 4 NSArray * array = [self allPropertyNames]; 5 6 // splicing parameter 7 NSMutableString * resultString = [[NSMutableString alloc] init]; 8 9 for (int I = 0; I <array. count; I ++) {10 11 // obtain the get Method 12 SEL getSel = [self creatGetterWithPropertyName: array [I]; 13 14 if ([self respondsToSelector: getSel]) {15 16 // obtain the class and method signature 17 NSMethodSignature * signature = [self methodSignatureForSelector: getSel]; 18 19 // obtain the call object from the signature 20 NSInvocation * invocation = [NSInvocation invocationWithMethodSignature: signature]; 21 22 // set target23 [invocation setTarget: self]; 24 25 // set selector26 [invocation setSelector: getSel]; 27 28 // receive the returned value 29 NSObject * _ unsafe_unretained returnValue = nil; 30 31 // call 32 [invocation invoke]; 33 34 // receive return value 35 [invocation getReturnValue: & returnValue]; 36 37 [resultString appendFormat: @ "% @ \ n ", returnValue]; 38} 39} 40 NSLog (@ "% @", resultString); 41 42}

 

After executing the above method, you can enter the attribute value in the Model. Next, after assigning the Model value to the main function, call the above method to output the Model attribute value. The call code is as follows:

1         BeautifulGirlModel *beautifulGirl = [BeautifulGirlModel modelWithDictionary:data];2         3         [beautifulGirl displayCurrentModleProperty];

  

The running result is as follows. The following output is the attribute value in the Model.

Iii. Different Processing Methods for the Key and Model attributes of Dictionary

Sometimes the attributes of the dictionary key and Model are different. How can this problem be solved? The simplest way is to maintain a ing method in a specific object class. Through this method, we can obtain the corresponding ing relationship.

1. add a method to the base class of the Model to return the ing dictionary, and rewrite it in the subclass. This ing method returns nil in the base class, if the subclass needs to be overwritten, this method will be overwritten and the ing dictionary will be returned. The method is as follows:

1 # ing between the property returned by pragma and the dictionary key 2-(NSDictionary *) propertyMapDic {3 return nil; 4}

 

2. modify our convenient initialization method. The method called in the case of a ing dictionary is different from that in the case of no ing dictionary. The code for convenient Initialization is as follows:

 1 - (instancetype)initWithDictionary: (NSDictionary *) data{ 2     { 3         self = [super init]; 4         if (self) { 5             if ([self propertyMapDic] == nil) { 6                 [self assginToPropertyWithDictionary:data]; 7             } else { 8                 [self assginToPropertyWithNoMapDictionary:data]; 9             }10         }11         return self;12     }13 }

 

3. next we will implement the method to be called with ing relationships. This method is to convert the dictionary key into a dictionary with the same name as the property through ing relationships, and then call the previous value assignment method, the Code is as follows:

1 # pragma assigns a value to the Model Attributes Based on the ing relationship. 2-(void) assg1_propertywithnomapdictionary: (NSDictionary *) data {3 // obtain the ing between the dictionary and the Model attributes. 4 NSDictionary * propertyMapDic = [self propertyMapDic]; 5 6 // convert the data into a dictionary with the same key and property, then call the assg1_propertywithdictionary Method 7 8 NSArray * dicKey = [data allKeys]; 9 10 11 NSMutableDictionary * tempDic = [[NSMutableDictionary alloc] initWithCapacity: dicKey. count]; 12 13 for (int I = 0; I <dicKey. count; I ++) {14 NSString * key = dicKey [I]; 15 [tempDic setObject: data [key] forKey: propertyMapDic [key]; 16} 17 18 [self assg1_propertywithdictionary: tempDic]; 19 20}

 

4. Create a BadBoyModel, override the propertyMapDic method, and provide the ing relationship in the propertyMapDic method, and return the dictionary corresponding to the ing relationship.

(1) BadBoyModel attributes are as follows:

1 // 2 // BadBoyModel. h 3 // BaseModelProject 4 // 5 // Created by Mr. luDashi on 15/7/24. 6 // Copyright (c) 2015 ludashi. all rights reserved. 7 // 8 9 # import "BaseModelObject. h "10 11 @ interface BadBoyModel: BaseModelObject12 13 @ property (nonatomic, copy) NSString * boy1; 14 @ property (nonatomic, copy) NSString * boy2; 15 @ property (nonatomic, copy) NSString * boy3; 16 @ property (nonatomic, copy) NSString * boy4; 17 18 @ end

 

(2) rewrite the ing method. The key of the ing dictionary is the key of the dictionary to be converted, and the Value is the attribute name of the corresponding Model.

1 // 2 // BadBoyModel. m 3 // BaseModelProject 4 // 5 // Created by Mr. luDashi on 15/7/24. 6 // Copyright (c) 2015 ludashi. all rights reserved. 7 // 8 9 # import "BadBoyModel. h "10 11 @ implementation BadBoyModel12 13 # ing between pragma returned attributes and dictionary keys 14-(NSDictionary *) propertyMapDic {15 return @ {@" keyBoy1 ": @" boy1 ", 16 @ "keyBoy2": @ "boy2", 17 @ "keyBoy3": @ "boy3", 18 @ "keyBoy4": @ "boy4 ",}; 19} 20 21 @ end

 

5. Test the main function.

(1) generate our numerical dictionary. The dictionary key is different from the attribute of the Model to be assigned a value. The following loop is to generate the data used for testing:

1 // generate a dictionary with different Dic keys and Model attributes. 2 3 NSMutableDictionary * data1 = [[NSMutableDictionary alloc] init]; 4 5 // create a dictionary for Testing 6 for (int I = 1; I <= 4; I ++) {7 NSString * key = [NSString stringWithFormat: @ "keyBoy % d", I]; 8 9 NSString * value = [NSString stringWithFormat: @ "I'm % d bad boy", I]; 10 11 [data1 setObject: value forKey: key]; 12}

 

(2) instantiate the Model and output the result. Of course, the previous code can also be used.

1         BadBoyModel *badBoyModel = [BadBoyModel modelWithDictionary:data1];2         3         [badBoyModel displayCurrentModleProperty];

 

The output result is as follows:

  

 

This is the blog today. Now, the most basic method encapsulation of the Model base class is almost the same. You can add new methods as needed.

Related Article

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.