When we define a property of an object that does not require a set method to modify the assignment, we add readOnly to the property.

1. Normal assignment

This results in an error when modifying a readOnly modified property using the set method

Assignment to readonly property
Copy the code

2. There are problems

Properties modified by readonly can still be modified by KVC.

3. How do I prevent KVC from modifying readOnly attributes

Rewrite the custom class “accessInstanceVariablesDirectly” method, make its return value is NO. Core code:

+(BOOL)accessInstanceVariablesDirectly{
    return NO;
}

Copy the code

This will cause an error when modified via KVC

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

Principle: 4.

When setValue:forKey: is used to set the value of an object property, the system looks for the corresponding key in the following order:

Set <key> = set<key> 2. If the above method is not found, the received message object class methods "accessInstanceVariablesDirectly" returns YES (the default returns YES), and then continue to find in the following order; 3. The sequence of _<key>, _is< key>, <key>, and is< key> is to check whether there is a corresponding key. If there is a corresponding key, the value of the key is changed. 4. Finally didn't find the corresponding access method or instance variables, and then into the setValue: forUndefinedKey: throw exceptions as follows: "reason: '[<Animal 0x60400001ec70> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key namekk.'Copy the code

Key point is in step 2 above accessInstanceVariablesDirectly method calls, the system default is to return, YES, we will be rewritten the method, to let it return NO, thus directly into the setValue: forUndefinedKey: method, and an exception is thrown, Prompt!

Modify the value of the readonly modifier property!