美文网首页
UI总结-KVC赋值

UI总结-KVC赋值

作者: Dear丶Musk | 来源:发表于2016-05-28 21:03 被阅读143次

                   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

    运行结果:

    相关文章

      网友评论

          本文标题:UI总结-KVC赋值

          本文链接:https://www.haomeiwen.com/subject/rxafdttx.html