KVC principle and ioskvc principle for iOS Learning
1. Implementation principle of KVC
- Traverse all keys in the dictionary. Take name as an example.
Find the setName: Method in the model and call the value assignment directly.
If the setName: method is not found, the system will continue to find whether the _ name attribute exists. If yes, the value of _ name = value is assigned.
If _ name is not found, the system will continue searching for the name attribute in the model.
If it is not found, an error is reported.
Error message:
KVC is mainly used to assign values to the model. It is best to define the desired attributes of the model, but sometimes it is different from the data we get. The following are several common cases:
- When we get more data than the model attribute, the above error will occur according to the KVC principle. Solution: rewrite setValue: forUndefinedKey: method in the. m file of the model.
#import "ZFFlag.h"@implementation ZFFlag- (void)setValue:(id)value forUndefinedKey:(NSString *)key{ }@end
- When the required property type is different from the data type, solution: rewrite the property setter method (according to the KVC search order)
If you need an image in the view, but the obtained data is generally the image name, that is, an NSString * type data, please refer to the Code for specific solutions.
# Import <Foundation/Foundation. h> # import <UIKit/UIKit. h> @ interface ZFFlag: NSObject @ property (nonatomic, strong) NSString * name; @ property (nonatomic, strong) UIImage * icon; // rewrite the setter method of the icon, note that the type is the type of the property in the obtained data-(void) setIcon :( NSString *) icon {_ icon = [UIImage imageNamed: icon];} // anti-crash-(void) setValue :( id) value forUndefinedKey :( NSString *) key {}@ end
# Import "ZFFlagView. h "# import" ZFFlag. h "@ interface ZFFlagView () @ property (weak, nonatomic) IBOutlet UILabel * label; @ property (weak, nonatomic) IBOutlet UIImageView * imageView; @ end @ implementation ZFFlagView-(void) setFlag :( ZFFlag *) flag {_ flag = flag; // assign _ label to the Child control. text = flag. name; _ imageView. image = flag. icon;} @ end