OC-KVC--就字典中的内容按照key值 对应的写入对象中
.main.m文件
/*
定义Student类
1、属性有age,name,gender; 2、age使⽤用assign,name使⽤用retain,gender使⽤用copy; 3、重写age、name、gender的setter和getter⽅方法。
*/
if 0
Student *stu = [[Student alloc] init];
// KVC 间接访问的一种方式
[stu setValue:@"longlong" forKey:@"name"];
NSLog(@"%@", [stu valueForKey:@"name"]);
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"long", @"name", @"m", @"gender", @"23", @"age", @"200", @"id", nil];
// 重要方法 就字典中的内容按照key值 对应的写入对象中
[stu setValuesForKeysWithDictionary:dic];
NSLog(@"%@ %@",stu.name, stu.gender);
Student.h文件
@interface Student : NSObject
@property (nonatomic, retain) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *gender;
@property (nonatomic, copy) NSString *idstr;
(instancetype)initWithName:(NSString *)name
age:(NSInteger)age gender:(NSString *)gender;
(instancetype)StudentWithName:(NSString *)name
age:(NSInteger)age gender:(NSString *)gender;
Student.m文件
@synthesize age = _age;
@synthesize name = _name;
@synthesize gender = _gender;
- (void)dealloc
{
[_name release];
[_gender release];
[super dealloc];
} (void)setName:(NSString *)name {
if (_name != name) {[_name release]; _name = [name retain];
}
}- (NSString *)name {
return [[_name retain] autorelease];
} (void)setGender:(NSString *)gender {
if (_gender != gender) {[_gender release]; _gender = [gender copy];
}
}- (NSString *)gender {
return [[_gender retain] autorelease];
} - (void)setAge:(NSInteger)age {
_age = age;
} - (NSInteger)age {
return _age;
} (instancetype)initWithName:(NSString )name age:(NSInteger)age gender:(NSString )gender
{
self = [super init];
if (self) {self.name = name; self.gender = gender; self.age = age;
}
return self;
}- (instancetype)StudentWithName:(NSString )name age:(NSInteger)age gender:(NSString )gender
{
Student *p = [[Student alloc] initWithName:name age:age gender:gender];
return [p autorelease];
}
//
(void)setValue:(id)value forKey:(NSString *)key
{[super setValue:value forKey:key];
if ([key isEqualToString:@"age"]) {// 其他类型转NSInteger类型 self.age = [value integerValue];
}
}
// 重定义setValue // KVC 时 不崩溃
(void)setValue:(id)value forUndefinedKey:(NSString *)key
{// 如上面
}
当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »