定义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