Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - IOS modifies private properties &; & member variable (KVC)
IOS modifies private properties &; & member variable (KVC)
Modifying private properties is a common scene in our daily development. For example, modify the property of a third-party library, but the third-party library does not disclose the property in the header file. Generally speaking, there are two schemes to modify private properties: KVC and runtime. Today, we will not introduce the principle here, but only the practice.

General idea: inherit the class to be modified, obtain the attribute or member variable to be modified, change its value, and then assign it to the class.

The following example inherits the parent class ZXParentViewController from the subclass ZXSonViewController and demonstrates it in the viewDidLoad method.

The parent class defines the private property name.

A subclass inherits the parent class and is modified by KVC.

The Api used at this time is changed from [setValue: forKey:] to [setValue:forKeyPath:].

The parent class uses one of the custom classes as a property.

Subclasses are modified by [setValue:forKeyPath:].

When a member variable is modified.

subclasses

Because struct itself does not follow the KVC protocol, we can convert it into NSValue.

The parent class uses enumerations as member variables.

Subclasses modify variables of parent class members in five steps.

The screenshot is as follows

Look at the printout.

The methods of modifying private attributes or member variables through KVC are basically listed, but it should be noted that KVC itself belongs to hard-coded form, which is easy to operate and flashback, and should be well protected when used.