KVC and Setvalue:forundefinedkey: Methods

Source: Internet
Author: User

In the process of actual development and application, it is often encountered that the key of the dictionary constructed by external data is more than the number of attributes in the custom data model.

For example: data obtained from the external JSON format contains 5 keys, as follows:

{    "cityname": "Beijing",    "state1": "0",    "State2": "1",    "tem1": "+",    "tem2": "14",}

The corresponding model contains only 3 properties:

*/* * * * *cityname;  /* * * *tem1;    /*  */*tem2;

The code for the entire sample program is as follows:

Controller VIEWCONTROLLER.M:

#import "ViewController.h"#import "Weather.h"@interfaceViewcontroller ()@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //reading external data in JSON formatNsurl *url = [[NSBundle mainbundle] Urlforresource:@"Weather"Withextension:@"JSON"]; NSData*data =[NSData Datawithcontentsofurl:url]; Nsdictionary*dict =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:NULL]; //Data Model InstancesWeather *w =[Weather weatherwithdictionary:dict]; NSLog (@"%@", W);}@end

Model class Weather.h:

#import<Foundation/Foundation.h>@interfaceWeather:nsobject/** City Name*/@property (copy, nonatomic) NSString*CityName;/** Minimum temperature*/@property (copy, nonatomic) NSNumber*tem1;/** Maximum temperature*/@property (copy, nonatomic) NSNumber*tem2;-(Instancetype) Initwithdictionary: (Nsdictionary *) dict;+ (Instancetype) weatherwithdictionary: (Nsdictionary *) dict;@end

Model class WEATHER.M:

#import "Weather.h"@implementationWeather-(Instancetype) Initwithdictionary: (Nsdictionary *) dict { self=[Super Init]; if(Nil! =Self )    {[Self setvaluesforkeyswithdictionary:dict]; }    returnSelf ;}+ (Instancetype) weatherwithdictionary: (Nsdictionary *) Dict {return[Self alloc] initwithdictionary:dict];}-(NSString *) Description {return[NSString stringWithFormat:@"[CityName, tem1, tem2] = [%@,%@,%@]", Self.cityname, Self.tem1, self.tem2];}@end

At this point, if you run the program, the following error message is reported:

Terminating app due to uncaught exception ' nsunknownkeyexception ', Reason: ' [Setvalue:forundefinedkey:]: This class I s not key value coding-compliant for the key state1. ' First throw call stack: (0 corefoundation 0x000000010e158c65 __exceptionpreprocess + 1651 Libo Bjc. A.dylib 0x000000010ddefbb7 Objc_exception_throw + 452 corefoundation 0x00000001 0E1588A9-[nsexception Raise] + Foundation 0x000000010d984b53-[nsobject (nskeyvaluecoding) s Etvalue:forkey:] + 2594 Foundation 0x000000010d9c6fad-[nsobject (nskeyvaluecoding) setvaluesfor Keyswithdictionary:] + 2615 2015-05-05-setvalueforundefinedkey 0x000000010d8b94bd-[weather initWithDictionary:] + 141 6 2015-05-05-setvalueforundefinedkey 0x000000010d8b9557 +[weather weatherwithdictionary:] + 877 2015-05-05-SETVALUEFO            Rundefinedkey 0x000000010d8b9925-[viewcontroller viewdidload] + 2778 UIKit                   0x000000010e683210-[uiviewcontroller loadviewifrequired] + 7389 UIKit 0x000000010e68340e-[uiviewcontroller View] + 2710 UIKit 0x000000010e59e2c9-[uiwindow AddR Ootviewcontrollerviewifpossible] + 5811 UIKit 0x000000010e59e68f-[uiwindow _sethidden:forc Ed:] + 24712 UIKit 0x000000011bb4a175-[uiwindowaccessibility _orderfrontwithoutmakingkey]                               + 6813 UIKit 0x000000010e5aae21-[uiwindow makekeyandvisible] + 4214 UIKit 0x000000010e54e457-[uiapplication _callinitializationdelegatesformainscene:transitioncontext:] + 273215 U Ikit 0x000000010e5511de-[uiapplication _runwithmainscene:transitioncontext:completion:] + 1 34916 UIKit 0x000000010e5500d5-[uiapplication workspacedidendtransaction:] + 17917 FRONTB            Oardservices      0x0000000110d575e5 __31-[fbsserialqueue performasync:]_block_invoke_2 + 2118 corefoundation 0x 000000010e08c41c __cfrunloop_is_calling_out_to_a_block__ + 1219 corefoundation 0x000000010e082165 __                      Cfrunloopdoblocks + 34120 corefoundation 0x000000010e081f25 __cfrunlooprun + 238921 corefoundation 0x000000010e081366 cfrunlooprunspecific + 47022 UIKit 0X000000010E54FB -[uiapplication _run] + 41323 UIKit 0x000000010e552900 Uiapplicationmain + 128224 2015- 05-05-setvalueforundefinedkey 0x000000010d8b9c7f main + 11125 libdyld.dylib 0x0000000110727145 STA                                 RT + 126??? 0x0000000000000001 0x0 + 1) libc++abi.dylib:terminating with uncaught exception of type NSException

When using the Setvaluesforkeyswithdictionary: method, the system automatically calls Setvalue:forundefinedkey when a property is missing in the data model that cannot be paired with Ningho: This method, The default implementation of the method throws a Nsundefinedkeyexceptiony exception.

If you want the program to run without throwing any exception information and working properly, you can have the data model class override the Setvalue:forundefinedkey: method to override the default implementation, and you can get the non-pairing key value from the two parameters of this method.

Modified Model WEATHER.M:

#import "Weather.h"@implementationWeather-(Instancetype) Initwithdictionary: (Nsdictionary *) dict { self=[Super Init]; if(Nil! =Self )    {[Self setvaluesforkeyswithdictionary:dict]; }    returnSelf ;}//overriding Setvalue:forundefinedkey: Methods- (void) SetValue: (ID) value Forundefinedkey: (NSString *) Key {NSLog (@"key =%@, value =%@", key, value);}+ (Instancetype) weatherwithdictionary: (Nsdictionary *) Dict {return[Self alloc] initwithdictionary:dict];}-(NSString *) Description {return[NSString stringWithFormat:@"[CityName, tem1, tem2] = [%@,%@,%@]", Self.cityname, Self.tem1, self.tem2];}@end

In this example, rewrite the Setvalue:forundefinedkey: method but do not make any substantive operations on any key values that could not be paired to ignore them. Of course, the key values can also be processed in the method body.

After the modification, run the program output as follows:

Key = state1, value = 0key = state2, value = 1[cityname, Tem1, tem2] = [Beijing, 25, 14]

KVC and Setvalue:forundefinedkey: Methods

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.