在使用kvc进行赋值的时候,有时候会遇到null值,这个时候我们使用kvc会报错

在使用kvc进行赋值的时候,有时候会遇到null值,这个时候我们使用kvc会报错,如何解决

 控制器代码如下:

//
//  ViewController.m
//  02-模型中的赋值
//
//  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:1 timeoutInterval:4.0f];
    // queue  如果给一个nil  那么就是没有队列。
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSLog(@"%@",result);
        Message *mes = [[Message alloc] init];
        [mes setValuesForKeysWithDictionary:result];
        NSLog(@"%@",mes);
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

message的.h文件

#import <Foundation/Foundation.h>

@interface Message : NSObject

@property(nonatomic,assign)int  messageId;

@property(nonatomic,copy)NSString *message;

@end

message的.m文件

#import "Message.h"

@implementation Message
/**
 *  NSLog的时候会调用这个方法
 *
 *  @return <#return value description#>
 */
- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@:%p>{messageId:%d,message:%@}",self.class,self,_messageId,_message];
}
@end

dome.json

{
    "messageId" : null,
    "message" : "明天天气怎么样"
}

在运行这段代码后会有报错 , 报错提示如下:

'[<Message 0x7f91785965f0> setNilValueForKey]: could not set nil as the value for the key messageId.'

原因就处在了kvc 自动赋值这里,由于messageId的返回值是null,而message的属性中int 类型的messageId 是不可以为空的。所以就会报错,那么如何更改这个错误呢,我们在网络开发中所有的数值类型都需要用NSNumber进行修饰,而不是采用int去修饰,更改message的.h文件,如下代码

#import <Foundation/Foundation.h>

@interface Message : NSObject

@property(nonatomic,assign)NSNumber * messageId;

@property(nonatomic,copy)NSString *message;

@end
原文地址:https://www.cnblogs.com/pengpengzhang/p/4845955.html