如何防止修改readonly修饰的属性值

当咱们的对象的某些个属性不须要对外提供set方法修改赋值时,那么咱们在定义属性时会给属性添加readonly。bash

1.正常赋值

这样经过set方法修改readonly修饰的属性时,会报错ui

Assignment to readonly property
复制代码

2.存在问题

对于readonly修饰的属性仍是能够经过KVC修改的。this

3.如何防止KVC修改readonly修饰的属性

重写自定义类的“accessInstanceVariablesDirectly”方法,让其返回值为NO。 核心代码:spa

+(BOOL)accessInstanceVariablesDirectly{
    return NO;
}

复制代码

这样再经过KVC修改时会报错.net

reason: '[<Animal 0x600000019e40> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.'
复制代码

4.原理:

当使用setValue:forKey:来设置对象属性的值时系统会按一下顺序来查找对应的key:code

1.查找是否存在set<key>:这样格式的方法;

2.若是上面方法未找到,则接受消息对象的类方法“accessInstanceVariablesDirectly”会返回YES(默认返回YES),再按下面顺序继续查找;

3._<key> , _is<Key> , <key> , is<Key> 的顺序查找是否存在对应的key,若是找到将改变key所对应的值。

4.最后仍是没有找到对应的存取方法或者实例变量,那么将走进 setValue:forUndefinedKey: 抛出以下异常:

reason: '[<Animal 0x60400001ec70> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key namekk.'
复制代码

关键点便在上面的第2步accessInstanceVariablesDirectly方法的调用,系统默认是返回YES,咱们将该方法重写后,让其返回NO,这样就直接走进setValue:forUndefinedKey:方法,并抛出异常,进行提示!对象

原文引用:修改readonly修饰属性的值!blog

相关文章
相关标签/搜索