---------------
main.m
---------------
#import
<Foundation/Foundation.h>
@interface
FKApple : NSObject
@end
@implementation
FKApple
- ( void ) setValue:( id )value forUndefinedKey:( id )key
{
- ( void ) setValue:( id )value forUndefinedKey:( id )key
{
NSLog(@"您尝试设置的key:【%@】并不存在!", key);
NSLog(
@"
您尝试设置的
value
为
:%@"
, value);
}
- ( id ) valueForUndefinedKey:( id )key
{
- ( id ) valueForUndefinedKey:( id )key
{
NSLog(@"您尝试访问的key:【%@】并不存在!", key);
return
nil
;
}
@end
int
main()
{
FKApple* app = [[FKApple alloc] init];
[app setValue: @" 大苹果 " forKey: @"name" ];
[app valueForKey: @"name" ];
{
FKApple* app = [[FKApple alloc] init];
[app setValue: @" 大苹果 " forKey: @"name" ];
[app valueForKey: @"name" ];
}
一、编写本节代码的具体步骤:
1.可仿照第二章001节的代码编写步骤,可以把类的接口文件,类的实现文件写在main.m文件中。
二、本节代码涉及到的知识点:
1.如果我们使用KVC来操作并不存在的属性(既没有set/get方法,也没有成员变量),
KVC将会自动调用 setValue:forUndefinedKey: 和 valueForUndefinedKey: 两个方法。
2.不过,这两个方法的实现必须由我们自己来写,如果我们不写,系统还是会报错。
3.这两个方法可以不声明,因为只要写了方法的实现,KVC就会自动找到它们。