? ? ? ? ? ? ? ?UI總結-KVC賦值
? ? ? 在實際的項目階段,后臺給我們的數據都是以字典的形式.我們在拿到數據的時候要如何操作才能將數據轉化為我們能用的數據,這時候我們就要用到KVC賦值了.
Viewcontroller.m文件:
#import "ViewController.h"
#import "Student.h"
@interface ViewController ()
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic ,retain)NSMutableArray *stuArr;
@property(nonatomic, retain)NSMutableArray *modelArr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self creatData];
self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
[self.view addSubview:self.tableView];
self.tableView.dataSource =self;
self.tableView.delegate = self;
// Key-Value-Coding
Student *stu = [[Student alloc]init];
[stu setValue:@"鳴人" forKey:@"name"];
NSLog(@"%@",stu.name);
NSLog(@"%@",[stu valueForKey:@"name"]);
self.modelArr = [NSMutableArray array];
for (NSDictionary *dic in self.stuArr) {
Student *stu = [[Student alloc]init];
//kvc進行賦值
[stu setValuesForKeysWithDictionary:dic];
NSLog(@"%@",stu.name);
[self.modelArr addObject:stu];
}
}
-(void)creatData{
NSString *path = [[NSBundle mainBundle]pathForResource:@"Student" ofType:@"plist"];
self.stuArr = [NSMutableArray arrayWithContentsOfFile:path];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.modelArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *reuse = @"reuse";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
}
Student * stu = self.modelArr[indexPath.row];
cell.textLabel.text = stu.name;
return cell;
}
Student.h文件:
#import<Foundation/Foundation.h>
@interface Student : NSObject
@property(nonatomic, copy)NSString *name;
@property(nonatomic, copy)NSString *age;
@property(nonatomic, copy)NSString *phone;
@property(nonatomic, copy)NSString *address;
@property(nonatomic, copy)NSString *hobby;
@end
Student.m文件:
#import "Student.h"
@implementation Student
//KVC的容錯方法
//只要在賦值過程中,沒有找到對應的屬性,就會自動調用這個方法,這個方法里如果沒有其他操作可什么都不寫.
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
@end