如果不先调用 setValueForKey,我会得到什么值?

What value will I get if not call setValueForKey first?

我在 viewController 中设置了 3 UITextField

@property(nonatomic,retain) UITextField *line1;
@property(nonatomic,retain) UITextField *line2;
@property(nonatomic,retain) UITextField *line3;

然后我尝试获取键的值:

for (int i = 1; i <= 3; i++)
{
    NSString *fieldName = [NSString stringWithFormat:@"line%d",i ];
    UITextField *theField = [self valueForKey:fieldName];
    NSLog(@"TEXTFIELD : %@",theField);
}

我得到了所有的 UITextFields。

2015-03-03 10:32:32.776 KVCTEST[26691:1586602] TEXTFIELD : <UITextField: 0x7f9a00e1c5c0; frame = (50 120; 220 30); text = ''; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7f9a00e1ae40>>
2015-03-03 10:32:32.777 KVCTEST[26691:1586602] TEXTFIELD : <UITextField: 0x7f9a00f1b920; frame = (50 160; 220 30); text = ''; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7f9a00f1bb80>>
2015-03-03 10:32:32.777 KVCTEST[26691:1586602] TEXTFIELD : <UITextField: 0x7f9a00f1d330; frame = (50 200; 220 30); text = ''; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7f9a00f1d590>>

但是如果我将实例变量名称更改为例如LINE1LINE2LINE3,将引发异常。

那么key-value-coding是不是默认会关联到ivar的名字呢?我不必先 setValueForKey 吗?

您可以在 Apple documentation regarding KVC 中找到您的答案。

A key is a string that identifies a specific property of an object. Typically, a key corresponds to the name of an accessor method or instance variable in the receiving object. Keys must use ASCII encoding, begin with a lowercase letter, and may not contain whitespace.