一个类里有实例变量,但没有设置Setter和Getter方法,也没有初始化方法,这时候如果想要在外界给他赋值就可以使用KVC
Person.h
#import <Foundation/Foundation.h>
#import "KVC.h"
@interface Person : NSObject
{
NSString *_name;
NSString *_sex;
KVC *_kvc;
int _age;
}
- (void)sayHi;
@end
Person.m
#import "Person.h"
#import "KVC.h"
@implementation Person
- (void)dealloc
{
//[_kvc release];
[_sex release];
[_name release];
[super dealloc];
}
- (id)init
{
self = [super init];
if (self) {
_kvc = [[KVC alloc] init];
}
return self;
}
- (void)sayHi
{
NSLog(@"name == %@",_name);
[_kvc text];
}
// 为没有定义的钥匙赋值 (如果在外界给变量赋值时,没有在类中找到这个变量,就会调用这个方法.如果没有这个方法程序就会崩溃)
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
}
@end
在外界赋值
#import "AppDelegate.h"
#import "Person.h"
@implementation AppDelegate
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
Person *p = [[Person alloc] init];
[p setValue:@"张三" forKey:@"name"];
[p setValue:@"nan" forKey:@"sex"];
[p setValue:@"fdsf" forKeyPath:@"kvc.text"];
[p sayHi];
return YES;
}