"iOS problem" dictionary to model, number of attributes mismatch problem

Source: Internet
Author: User

The problem of the mismatch between the key-value pairs and the model properties of the dictionary-to-model

1. Number of keys in the dictionary < number of attributes of the model (key can match the properties of the model)

1>. KVO Way:

-Setvaluesforkeyswithdictionary:

2> for loop, assign each value

2. Number of keys in the dictionary = number of properties of the model (key can match the properties of the model)

The same 1.

3. Number of dictionaries > number of attributes of the model (the properties of the model are part of the dictionary key)

A total of three ways to solve

Second, the solution:

Create a Gxapp model that declares two attributes: name (name) details, which are used directly in the class method

  

  

  

  

Used in the controller:

  

Run directly:

Terminating app due to uncaught exception ' Nsunknownkeyexception ',

Reason: ' [<gxapp 0x7ff1a8d41790> Setvalue:forundefinedkey:]: This class was not key value coding-compliant for the KE Y version. '

Solution One:

In a class method, each property is assigned a value

  

1 //2 //gxapp.m3 //property mismatch Problem of b01-dictionary to model4 //5 //Created by Gxiangzi on 15/8/25.6 //Copyright (c) 2015 Hqu. All rights reserved.7 //8 9 #import "GXApp.h"Ten  One @implementationGxapp A  -+ (Instancetype) Appwithdict: (nsdictionary*) Dict - { thegxapp* app =[[Gxapp alloc] init]; -  -     //using the properties of the array storage model -nsarray* parameters = @[@"name",@"Details" ]; +     //iterate through the dictionary to determine if the model has this property -[Parameters enumerateobjectsusingblock:^ (IDobj, Nsuinteger idx, bool*stop) +     { A         if(Dict[obj]) at         { - [app Setvalue:dict[obj] forkey:obj]; -         } -     }]; -  -     returnapp; in } -  to @end

Cons: This approach is relatively simple for very few attributes, but not very scalable.

Solution Two

Run is the mechanism, at run time, to judge the properties of the model, and then assign the value

  

1 //2 //gxapp.m3 //property mismatch Problem of b01-dictionary to model4 //5 //Created by Gxiangzi on 15/8/25.6 //Copyright (c) 2015 Hqu. All rights reserved.7 //8 9 #import "GXApp.h"Ten #import<objc/runtime.h> One  A @implementationGxapp -  -+ (Instancetype) appwithdict: (Nsdictionary *) Dict the { -Gxapp *app =[[Gxapp alloc] init]; -      -Nsarray *array =[app GetProperties]; +      -      +     //take the corresponding value in the data dictionary according to the value of the property A[Array enumerateobjectsusingblock:^ (IDobj, Nsuinteger idx, BOOL *stop) { at         //The value of the key property. -NSString *key =obj; -          -         if(Dict[key]) { -              - [app Setvalue:dict[key] Forkey:key]; in         } -          to     }]; +      -     returnapp; the } *  $ //gets the properties of a class dynamically.Panax Notoginseng-(Nsarray *) GetProperties - { theUnsignedintcount; +      A     //get the properties in a class theobjc_property_t *properties = Class_copypropertylist (self.class, &count); +      -Nsmutablearray *array =[Nsmutablearray array]; $      $     //traverse a property in a class to convert each property value to an OC string -      for(inti =0; I < count; i++) { -          the         //Pro remains a C-language data type -objc_property_t Pro =Properties[i];Wuyi          the         //Pointer to a C language string. -         Const Char*name =property_getname (pro); Wu          -NSString *property =[[NSString alloc] initwithutf8string:name]; About          $ [Array addobject:property]; -     } -      -     returnArray; A } +  the @end

Cons: runtime Code, c code, code not easy to remember

Solution III,

   Rewrite-setvaluesforkeyswithdictionary:

  

////gxapp.m//property mismatch Problem of b01-dictionary to model////Created by Gxiangzi on 15/8/25.//Copyright (c) 2015 Hqu. All rights reserved.//#import "GXApp.h"@implementationGxapp+ (Instancetype) appwithdict: (Nsdictionary *) dict{Gxapp*app =[[Gxapp alloc] init];        [App Setvaluesforkeyswithdictionary:dict]; returnapp;}- (void) SetValue: (ID) value Forundefinedkey: (NSString *) key{// do nothing}@end

Explain:

Official explanation:

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


Given that invocation of-setvalue:forkey:would is unable to set the keyed value because the type of the parameter of The corresponding accessor method is a nsnumber scalar type or nsvalue structure type but the value is nil, set the keyed Value using some other mechanism. The default implementation of this method raises an nsinvalidargumentexception. You can override it to map nil values to something meaningful in the context of your application.

When using the KVO assignment, if the key value does not match, will be reported a nsinvalidargumentexception exception, you can override this method can be resolved

  

"iOS problem" dictionary to model, number of attributes mismatch problem

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.