iOS Development-Dictionary quick Assignment

Source: Internet
Author: User

In the past when learning to parse data, we use a method is a life, and then added to the dictionary, and then copy, the trouble, but also can not guarantee a success, no error, I have encountered several key value problems!

You can actually replace the copy process with one sentence:

[Test setvaluesforkeyswithdictionary:dic];

Question one: What happens to the model that does not exist with the elements in dic?

At this time, the console output is empty "= (null)"

Question two: What happens if the dictionary does not exist with the elements in the model?

Error, or crash, because there is no corresponding age attribute in the model, causing the program to crash

Workaround: Implement a method: Setvalue:forundefinedkey:, this method can filter out the non-existent key value,

Specific operation:

Add in Model

Add the. h file:

-(void) SetValue: (ID) value Forundefinedkey: (NSString *) key;

And it needs to be implemented in the M file:

-(void) SetValue: (ID) value Forundefinedkey: (NSString *) key{    }

There is no need to write any content in the method!

Question three: If the key in DIC is different from the variable name in model, how should I assign a value?

As we can see from the previous, the key in DIC is assigned to the attribute with the same name as key in the model.

If the key value in DIC is the name in Username,model, the keyword, and so on, should change.

Solution: Start with the Setvalue:forundefinedkey method.

Change the values in DiC, and the properties of the model species,

Perfect the Setvalue:forundefinedkey method in model:

-(void) SetValue: (ID) value Forundefinedkey: (NSString *) key{        if([Key isequaltostring :@ "ID"])        {            Self.age=value;        }         if ([Key isequaltostring:@ "username"])        {            Self.name=value;        }    }

That's it! Of course, can also be directly in the DIC and model inside change into a consistent!

iOS Development-Dictionary quick Assignment

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.