1.简介
KVC:Key-Value Coding,直译是:键值编码。简单来讲,就是给属性设置值的 比如说如下的第一行KVC的代码,其实和第二行的普通代码是等效的:
UITableViewController *vc = [segue destinationViewController];
kvc: [vc setValue:self.textField.text forKey:@"startTime"];
vc.startTime = self.textField.text;
KVC的代码会编译成这样:
SEL sel = sel_get_uid ("setValue:forKey:");
IMP method = objc_msg_lookup (myClass->isa,sel);
method(site, sel, self.textField.text, @"startTime");
KVC内部的实现实际上是这样的:一个对象在调用setValue的时候:
a. 首先根据方法名找到运行方法的时候所需要的环境参数。
b. 它会从自己isa指针结合环境参数,找到具体的方法实现的接口。
c. 再直接查找得来的具体的方法实现。
a. 首先根据方法名找到运行方法的时候所需要的环境参数。
b. 它会从自己isa指针结合环境参数,找到具体的方法实现的接口。
c. 再直接查找得来的具体的方法实现。
2.demo示例:
// KVCTableViewCell.h
// KVC
//
// Created by tinghou on 16/5/30.
//
//
#import <UIKit/UIKit.h>
@interface KVCTableViewCell : UITableViewCell
- (id)initWithReuseIdentifier:(NSString*)identifier;
// Object to display.
@property (nonatomic, readwrite, strong) id object;
// Name of property of object to display
@property (nonatomic, readwrite, copy) NSString *property;
@end
//
// KVCTableViewCell.m
// KVC
//
// Created by tinghou on 16/5/30.
//
#import "KVCTableViewCell.h"
@implementation KVCTableViewCell
- (BOOL)isReady {
return (self.object && [self.property length] > 0);
}
- (void)update {
NSString *text;
if (self.isReady) {
id value = [self.object valueForKeyPath:self.property];
text = [value description];
}
else {
text = @"";
}
self.textLabel.text = text;
}
- (id)initWithReuseIdentifier:(NSString *)identifier {
return [self initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier];
}
- (void)setObject:(id)anObject {
_object = anObject;
[self update];
}
- (void)setProperty:(NSString *)aProperty {
_property = aProperty;
[self update];
}
@end
//
// KVCTableViewController.m
// KVC
//
// Created by tinghou on 16/5/30.
//
#import "KVCTableViewController.h"
#import "KVCTableViewCell.h"
@implementation KVCTableViewController
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"KVCTableViewCell";
KVCTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[KVCTableViewCell alloc]
initWithReuseIdentifier:CellIdentifier];
cell.property = @"intValue";
}
cell.object = @(indexPath.row);
return cell;
}
@end