直接上CODE
Dream.m1 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| @interface Dream() { NSString *_dream; NSString *dream; } @end
@implementation Dream
-(instancetype)init{ self = [super init]; if (self) { _dream = @"Yume4"; dream = @"Yume5"; } return self; }
-(NSString *)getDream{ return @"Yume1H"; }
-(NSString *)dream{ return @"Yume2H"; }
-(NSString *)isDream{ return @"Yume3H"; }
-(NSString *)_getDream{ return @"Yume1M"; }
-(NSString *)_dream{ return @"Yume2M"; }
-(NSString *)_isDream{ return @"Yume3M"; }
-(id)valueForUndefinedKey:(NSString *)key{ if ([key isEqualTo:@"dream"]) { return @"Yume6"; } return nil; }
@end
|
Test Code1 2 3 4
| Dream *dream = [Dream new]; NSLog(@"%@",[dream valueForKey:@"dream"]);
|
在這篇簡報Intro to Cocoa KVC/KVO and Bindings(Page 13)上有提到KVC依序搜尋執行的順序
- Search for a public accessor (‘getLastName’ or ‘lastName’)
- If not found, search for a private accessor method based on key (‘_getLastName’ or ‘_lastName’).
- If not found’ search for an instance variable (_lastName or lastName)
- If not found, invoke valueForUndefinedKey:
實測
- 首先先找方法
getDream
-> dream
-> isDream
- 再找方法
_getDream
-> _dream
-> _isDream
- 再找 instance variable
_dream
-> dream
- 最後呼叫
valueForUndefinedKey: