[IOS] development-dictionary conversion model and KVC, ioskvc

Source: Internet
Author: User

[IOS] development-dictionary conversion model and KVC, ioskvc

Requirement 1: Convert the dictionary into the desired object. The attribute of the object is the dictionary key value. There are two disadvantages of directly using the key value to obtain data. One is that the key value is hard to remember, second, Xcode directly uses the key value without any smart prompts, which can easily lead to unknown errors. When using the model, you can click the dot syntax to point out the required data to ensure data accuracy. The advantage of using a model is that it is easy to store and transmit values, and is not prone to errors. Most importantly, this is also in line with the design patterns of MVC and MVVM.

 

Note: To use a model, KVC is required. If we input a dictionary from the outside, the values of two keys in the dictionary are required, the two values are "name" and "age" respectively ". When using KVC, note that the model attributes must correspond to the key values in the dictionary. For example, the "name" in the dictionary must have a name attribute in the model. In this way, you can use KVC. The two methods of KVC are as follows: (we have two model attributes by default, namely name and age, and the passed-in dictionary is dict by default)

 

1. setValue (model attribute, forKey: dictionary key value)

Eg: setValue (self. name, forKey: dict ["name"])

 

* This assignment method is very troublesome. Each time you need a key value, you must repeat this method. This assignment method is not much different from self. name = dict ["name "].

2. setValuesForKeysWithDictionary (input dictionary)

Eg: setValuesForKeysWithDictionary (dict)

* The Value assignment is completed directly. In fact, setValuesForKeysWithDictionary (the passed dictionary), which also calls setValue (model attribute, forKey: dictionary key value) by default, and traverses the dictionary to assign values to model attributes one by one. Therefore, when using KVC, the attributes of the model must match the dictionary key values one by one.

Requirement 2: What if we only want to use the partial value in the dictionary? A large dictionary contains dozens of keys. Do we need to define dozens of attributes based on the key value in the model? Of course, our programmers are very lazy and will certainly not define so many key values. Now we only need to rewrite the following methods of KVC:

3. setValue (value: AnyObject ?, ForUndefinedKey key: String)

* This method will help us filter key values that we do not have. When the value is setValuesForKeysWithDictionary (dict), this method will be called when we monitor the attributes corresponding to the key values in the dictionary.

* You do not need to write any code During rewriting. If you want to print the key values, you can print them in some cases.

Requirement 3: We know that many dictionaries contain the key value "id. "Id" is a data type in iOS. Obviously, "id" cannot be defined as a model attribute name. At this time, we only need to define an attribute name to save the "id". Of course, to be more read and rigorous, we generally define it as "ID" most appropriate. We know that to use KVC, we need to have a pair of key values and Model names, but we just want to get the "id ". At this time, we need to combine "requirement 1" and "requirement 2. When obtaining the "id", we directly assign values using the passed dictionary: (in this case, we add a new attribute "ID ")

Eg: self. ID = dict ["id"]

* After the value is assigned, the value corresponding to the "id" is taken out.

However, we still need to obtain other values. At this time, setValuesForKeysWithDictionary (dict) is used to assign values to other attributes. Of course, you also need to override setValue (value: AnyObject ?, ForUndefinedKey key: String) method, because the dictionary contains the key value "ID" (the dictionary contains "id" and "ID" is the newly defined attribute of the model ). The complete code is as follows:

Swift:

Override init (){

Super. init ()

Self. ID = dict [@ "id"];

SetValuesForKeysWithDictionary (dict)

}

Override func setValue (value: AnyObject ?, ForUndefinedKey key: String ){}

OC:

+ (Instancetype) testWithDict :( NSDictionary *) dict {

TEST * test = [[TEST alloc] init];

Test. ID = dict [@ "id"];

[Test setValuesForKeysWithDictionary: dict];

Return test;

}

-(Void) setValue :( id) value forUndefinedKey :( NSString *) key {

}

* When Using KVC in object methods, you must first use super. init, because you must first ensure that an object exists so that you can access the attributes of this object.

* Note: When Using Object methods, the "W" in "With" must be capitalized; otherwise, super. init cannot be completed.

Eg:-(instancetype) initWithDict :( NSDictionary *) dict

Supplement: KVC is powerful not only in assigning values to models, but also in assigning values to read-only attributes and changing private attributes. For example, if tabBar in UITabBarController is a read-only attribute, you cannot assign a value to the read-only attribute.

SetValue (value, forKey: "attribute name ")

Eg: setValue (value, forKey: "tabBar ")

Summary: KVC is short for Set Value Coding. It is a mechanism that directly uses the string name (key) to define class attributes. Instead of using Setter and Getter ).

 

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.