setValuesForKeysWithDictionary 使用方法

本文介绍如何通过重写setValue:forUndefinedKey:方法来避免在使用setValuesForKeysWithDictionary自动填充模型属性时因缺失键而引发的应用崩溃。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义NSObject文件,setValuesForKeysWithDictionary 为自动将Dic赋值给模型文件,如果模型文件中没有对应的key值,就会崩溃,解决方法为下面,重写
- (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key
- 方法
即可拦截崩溃
%s (代表打印字符串 类似%c)func

import “student.h”

@implementation student
- (instancetype)initWithDic:(NSDictionary *)dict{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}

  • (instancetype) stuWithDict:(NSDictionary *)dict
    {
    return [[self alloc] initWithDic:dict];
    }
  • (void)setValue:(id)value forUndefinedKey:(nonnull NSString *)key
    {
    NSLog(@”拦截崩溃**%s”,func);
    }

@end

.m文件实现方式为:

import “student.h”

@implementation student
- (instancetype)initWithDic:(NSDictionary *)dict{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}

  • (instancetype) stuWithDict:(NSDictionary *)dict
    {
    return [[self alloc] initWithDic:dict];
    }
  • (void)setValue:(id)value forUndefinedKey:(nonnull NSString *)key
    {
    NSLog(@”拦截崩溃**%s”,func);
    }

@end

调用方式为:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@”Tom”,@”name”,@”110”,@”num”,@”170.0”,@”height”, nil];
student * stu = [[student alloc] initWithDic:dict];
NSLog(@”name = %@ num = %@”, stu.name, stu.num);

KVODEMO:
People.m

1 #import “People.h”
2 #import “Dog.h”
3
4 @implementation People
5
6 /**
7 * 初始化时增加对dog的监听
8 *
9 */
10 - (void)setDog:(Dog *)dog
11 {
12 _dog = dog;
13 [self.dog addObserver:self forKeyPath:@”name” options:NSKeyValueObservingOptionNew context:nil];
14 }
15 /**
16 * 重写observeValueForKeyPath方法
17 */
18 - (void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值