When using KVC to assign a value, sometimes you will encounter a null value, this time we use KVC will be error, how to solve
The controller code is as follows:
////VIEWCONTROLLER.M//02-Assignment in the model////Created by Jerry on 15/9/29.//Copyright (c) 2015 Jerry. All rights reserved.//#import"ViewController.h"#import"Message.h"@interface Viewcontroller () @end @implementation Viewcontroller- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{Nsurl*url = [Nsurl urlwithstring:@"Http://127.0.0.1/demo.json"]; Nsurlrequest*request = [Nsurlrequest requestwithurl:url cachepolicy:1timeOutInterval:4.0f]; //If you give a nil to a queue, there are no queues. [Nsurlconnection sendasynchronousrequest:request queue:[[nsoperationqueue Alloc]init] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {ID result= [Nsjsonserialization jsonobjectwithdata:data options:0Error:null]; NSLog (@"%@", result); Message*mes =[[Message alloc] init]; [Mes setvaluesforkeyswithdictionary:result]; NSLog (@"%@", MES); }]; }- (void) didreceivememorywarning {[Super didreceivememorywarning]; //Dispose of any resources the can be recreated.} @end
The. h file of the message
#import <Foundation/Foundation.h>@interface message:nsobject@property (nonatomic,assign)int * message; @end
The. m file for message
" Message.h " @implementation Message /* * * NSLog will call this method * */-(NSString *) description{ return [NSString stringWithFormat:@ "<%@:%p>{messageid:%d,message:%@}", self. class , Self,_messageid,_message];} @end
Dome.json
{ "messageId"null, "message " " What 's the weather like tomorrow " }
After running this code will have an error, the error message is as follows:
' [<message 0x7f91785965f0> Setnilvalueforkey]: Could not set nil as the value for the key messageId. '
The reason is in the KVC automatic assignment here, because the return value of MessageID is null, and the property of the message int type MessageID is not empty. So it will be an error, so how to change this mistake, we in the network development of all the numeric types need to be decorated with nsnumber, instead of using int to modify the. h file of the message, the following code
#import <Foundation/Foundation.h>@interface**message; @end
When using KVC to assign a value, sometimes you will encounter a null value, this time we use KVC will be error