Use Runtime for iOS development to assign values to the Model class, iosmodel

Source: Internet
Author: User

Use Runtime for iOS development to assign values to the Model class, iosmodel

This blog is a foundation for network caching. This blog first provides a simple and easy-to-use method for converting dictionaries into Entity classes, then, how to use Runtime to assign values to the Model object class is given. This blog will introduce part of this article, mainly because the dictionary key is the same as the Model attribute name and uses Runtime to assign values, in the next blog, we will provide a solution where the dictionary key value and Model name are different, and how to print the object class attribute value using Runtime.

Runtime in iOS development is powerful and flexible. Today's Blog content mainly uses a little bit of Runtime. Not much nonsense.

1. Create our test project

In this test project, the UI part developed by iOS is not used. Therefore, we create a project based on the system console. The main call code is of course placed in the main function, as shown in the Project creation process, Create new project-> OS X-> Application-> Command Line Tool-> one-way next. 2. Create test data.

1. first, use the for loop to create a dictionary. Of course, the keys and values of the dictionary are regular. The for loop below creates our test data. If there is a network request, the source of the test dictionary is the dictionary you parsed from the JOSN of the network request. No network request is made here, because the network request is not the focus of this blog, therefore, we use the for loop to generate a test dictionary for use. The code for creating a test dictionary is as follows. Place the code in the main function:

1 NSMutableDictionary * data = [[NSMutableDictionary alloc] initWithCapacity: 11]; 2 3 // create a dictionary suitable for testing 4 for (int I = 0; I <= 10; I ++) {5 NSString * key = [NSString stringWithFormat: @ "girl % d", I]; 6 7 NSString * value = [NSString stringWithFormat: @ "I'm % d Girl", I]; 8 9 [data setObject: value forKey: key]; 10}

 

The above code generates a dictionary and the printed result is as follows. We can see that the dictionary is unordered. Next we will use the data dictionary as the dictionary after the JSON resolution of our network request.

1 22:33:15. 742 BaseModelProject [65321: 3224966] data = {2 girl0 = "I am 0th girls"; 3 girl1 = "I am 1st girls "; 4 girl10 = "I'm 10th girls"; 5 girl2 = "I'm 2nd girls"; 6 girl3 = "I'm 3rd girls "; 7 girl4 = "I'm 4th girls"; 8 girl5 = "I'm 5th girls"; 9 girl6 = "I'm 6th girls "; 10 girl7 = "I'm 7th girls"; 11 girl8 = "I'm 8th girls"; 12 girl_9 = "I'm 9th girls"; 13}

 

3. Create an object class corresponding to the data dictionary

Next, an object class corresponding to the Data dictionary will be created. First, the attribute names and dictionary key values of the object class will be consistent, in the next blog, we will implement how to convert the dictionary of different key values into attributes of the object class.

1. First, create an entity class. This entity class must inherit from the entity base class, because some common methods are written in the Entity base class, such as the constructor, the initialization method is convenient, and the dictionary is converted to the Model attribute and other methods are abstracted to this base class. Shows how to create an object class. When creating a class, select the created base class:

BaseModelObject is the base class created previously. BaseModelObject can be inherited from NSObject.

1 // 2 // BeautifulGirlModel. h 3 // BaseModelProject 4 // 5 // Created by Mr. luDashi on 15/7/20. 6 // Copyright (c) 2015 ludashi. all rights reserved. 7 // 8 9 # import "BaseModelObject. h "10 11 @ interface BeautifulGirlModel: BaseModelObject12 13 @ property (nonatomic, copy) NSString * girl0; 14 @ property (nonatomic, copy) NSString * girl1; 15 @ property (nonatomic, copy) NSString * girl2; 16 @ property (nonatomic, copy) NSString * girl3; 17 @ property (nonatomic, copy) NSString * girl4; 18 @ property (nonatomic, copy) NSString * girl5; 19 @ property (nonatomic, copy) NSString * girl6; 20 @ property (nonatomic, copy) NSString * girl7; 21 @ property (nonatomic, copy) NSString * girl8; 22 @ property (nonatomic, copy) NSString * gird9; 23 @ property (nonatomic, copy) NSString * girl10; 24 25 @ end

 

4. Implement Methods in the Entity base class.

Methods In the base object class are abstracted from each Model and can be reused. Methods in the base object class generally include: generating the getter method and generating the setter method, obtain the attributes of the Model class, assign the dictionary value to the corresponding Model, and dynamically call the getter method to traverse the attribute values of the object class. The rest of this blog will be provided later.

1. Generate the set Method Based on the Key value

The first method to write is to input a string and then return the setter method of the attribute corresponding to the string. This method is actually very simple. It is to uppercase the first letter of the corresponding string and splice the set keyword to reproduce SEL and return it. The specific implementation of this method is as follows:

1 # pragma mark -- use a string to create the Setter method of the string and return 2-(SEL) creatSetterWithPropertyName: (NSString *) propertyName {3 4 // 1. upper letter 5 propertyName = propertyName. capitalizedString; 6 7 // 2. set keyword 8 propertyName = [NSString stringWithFormat: @ "set % @:", propertyName]; 9 10 // 3. return the set Method 11 return NSSelectorFromString (propertyName); 12}

 

2. the dictionary is passed into the method, and the dictionary value is assigned to the attributes of the corresponding object class. This method needs to call the above method to generate the setter method, the setter method is used to assign the dictionary Value to the attribute corresponding to the object class. The Code is as follows. The comments in the code below are more detailed. For details, refer to the following comments. By calling this method, you can assign the dictionary value to the attribute of the corresponding object class. The premise of calling this method is that the dictionary key must be the same as the attribute name of the object class. Some friends will ask what to do if they are different? This question will be introduced in the next blog.

1 /************************************** * *********************************** 2 * assign a dictionary attribute 3 * parameters of the current object class: dictionary 4 * Applicability: when the key of the data requested by the network is the same as the attribute of the object class, you can use this method to assign the dictionary Value 5 * to the attribute 6 ********** of the object class ********* **************************************** * *********************/7 8-(void) assg1_propertywithdictionary: (NSDictionary *) data {9 10 if (data = nil) {11 return; 12} 13 14 // 1. obtain the dictionary's key15 NSArray * dicKey = [data allKeys]; 16 17 // 2. the dictionary key is traversed cyclically and the setter method of the object class is dynamically generated. The Value of the dictionary is assigned to the attribute 19 for (int I = 0; I <dicKey. count; I ++) {20 21 // 2.1 use the getSetterSelWithAttibuteName method to obtain the set Method 22 SEL setSel = [self creatSetterWithPropertyName: dicKey [I]; 23 24 if ([self respondsToSelector: setSel]) {25 // 2.2 obtain the value26 NSString * value = [NSString stringWithFormat: @ "% @", data [dicKey [I]; 27 28 // 2.3 assign a value to the attributes of the object class through the setter method 29 [self defined mselec1_mainthread: setSel30 withObject: value31 waitUntilDone: [NSThread isMainThread]; 32} 33 34} 35 36}

 

3. The next step is to write the object class entry, that is, convenient initialization method and constructor. And leave the interface in the header file. The following describes the convenient initialization method and then the convenience constructor.

(1) The following code is a convenient Initialization Method of the object class, of course, an instance method. This method requires the input of a dictionary. The key in this dictionary is the attribute name of the object class, the value is the value to be assigned to the attribute of the object class. And return the instance of the object class. In short, the call-(void) assg1_propertywithdictionary: (NSDictionary *) data method is called. The specific code is as follows:

1 - (instancetype)initWithDictionary: (NSDictionary *) data{2     {3         self = [super init];4         if (self) {5              [self assginToPropertyWithDictionary:data];6         }7         return self;8     }9 }

  

(2) The convenience constructor will be provided below. Of course, the convenience constructor is a class method and an instance of this class will be returned. To put it bluntly, the constructor is the constructor that calls the convenience initialization method after memory allocation and returns the instance of the object. below is the constructor corresponding to the object class:

1 + (instancetype)modelWithDictionary: (NSDictionary *) data{2     3     return [[self alloc] initWithDictionary:data];4     5 }

 

5. Test the above Code

Run the code to check the results. Because this is a system-based console program, we need to call the method we compile in the main function. We need to pass the test dictionary generated above into the constructor of the object class, and obtains an instance of the object class. The attributes in the instance of the retrieved object class have been assigned the passed-in dictionary value. The calling method is as follows.

1         BeautifulGirlModel *beautifulGirl = [BeautifulGirlModel modelWithDictionary:data];2         3         NSLog(@"%@", beautifulGirl.girl0);

 

The running result is as follows:

1 BeautifulGirlModel * beautifulGirl1 = [[BeautifulGirlModel alloc] init]; 2 bytes = data [@ "girl0"]; 3 beautifulGirl1.girl1 = data [@ "girl1"]; 4 beautifulGirl1.girl2 = data [@ "girl2"]; 5 beautifulGirl1.girl3 = data [@ "girl3"]; 6 beautifulGirl1.girl4 = data [@ "girl4"]; 7 beautifulGirl1.girl5 = data [@ "girl5"]; 8 beautifulGirl1.girl6 = data [@ "girl6"]; 9 beautifulGirl1.girl7 = data [@ "girl7"];

 

  

 

This is the content in today's blog. The rest of the content will be introduced in the next blog. The content of the next blog is more useful than this blog.

 

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.