IOS KVC兼容

直接先來一段CODE

Yume.h
1
2
3
4
5
6
7
8
9

@interface Yume : NSObject

@property (nonatomic, strong) NSString *yume;

-(NSString *)yume1;

@end

Yume.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

@interface Yume ()
{
NSString *yume3;
}
@end

@implementation Yume

-(instancetype)init{
self = [super init];
if (self) {
_yume = @"dream";
yume3 = @"dream3";

}
return self;
}

-(NSString *)yume1{
return @"dream1";
}

-(NSString *)yume2{
return @"dream2";
}

-(id)valueForUndefinedKey:(NSString *)key{
if ([key isEqualTo:@"yume4"]) {
return @"dream4";
}
return nil;
}

@end

從官方文件就有提到Key-Value Coding Accessor Methods

In order for key-value coding to locate the accessor methods to use for invocations of valueForKey:, setValue:forKey:, mutableArrayValueForKey:, and mutableSetValueForKey:, you need to implement the key-value coding accessor methods.

為了讓KVC去定位存取方法並且調用,你必須實現這些KVC的存取方法

這邊我更深的理解為你必須實現KVC的存取方法,而不是property的存取方法

個人理解:property自動合成的存取方法是為了配合KVC的存取方法

接下來說明這個類別

  • yume 非常正常的property
  • yume1 寫在h檔的方法
  • yume2 寫在m檔的方法
  • yume3 在m檔的instance variable
  • yume4 沒定義
Test Code
1
2
3
4
5
6
7
8

Yume *yume = [Yume new];
NSLog(@"%@",[yume valueForKey:@"yume"]);
NSLog(@"%@",[yume valueForKey:@"yume1"]);
NSLog(@"%@",[yume valueForKey:@"yume2"]);
NSLog(@"%@",[yume valueForKey:@"yume3"]);
NSLog(@"%@",[yume valueForKey:@"yume4"]);