码迷,mamicode.com
首页 > 移动开发 > 详细

IOS开发过程中的KVC机制

时间:2016-03-30 12:58:23      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

作用:提供了另一种  为对象的属性赋值读取对象属性的编写代码的方式

—————Dog.h———————
@interface Dog : NSObject
@property(nonatomic,strong)NSString *name;

@end
----Book.h----
@interface Book : NSObject
@property(nonatomic,strong)NSString *name;
@property(nonatomic)float price;
@end
----Student.h---
#import <Foundation/Foundation.h>
#import "Dog.h"
#import "Book.h"

@interface Student : NSObject
{
    float _score;
}
@property(nonatomic,strong)NSString *name;
@property(nonatomic,strong)Dog *dog;
@property(nonatomic,strong)NSArray *books;
@end
---Student.m----
@implementation Student
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dog = [[Dog alloc]init];
        
        Book *b1 = [[Book alloc]init];
        b1.name = @"数学";
        b1.price = 35.5;
        
        Book *b2 = [[Book alloc]init];
        b2.name = @"语文";
        b2.price = 31.8;
        
        self.books = @[b1,b2];
    }
    return self;
}
@end

----ViewController.m----
#import "ViewController.h"
#import "Student.h"
Student *stu = [[Student alloc]init];
    
    //1.为私有成员赋值
    [stu setValue:@98 forKey:@"score"];
    [stu setValue:@"张3" forKey:@"name"];
   
    NSLog(@"%@ %@",[stu valueForKey:@"name"],[stu valueForKey:@"score"]);

    //2.访问id类型的对象
    id stu2 = [[Student alloc]init];
    [stu2 setValue:@"李4" forKey:@"name"];
    [stu2 setValue:@95.5 forKey:@"score"];

    NSLog(@"%@ %f",[stu2 valueForKey:@"name"],[[stu2 valueForKey:@"score"] floatValue]);
    
    //3.为层级类型的属性赋值
    [stu setValue:@"ww" forKeyPath:@"dog.name"];
    NSLog(@"%@",stu.dog.name);
    
    //4.使用自带的运算符对数组属性进行运算
    //获取所有图书的价格
    NSLog(@"%@",[stu valueForKeyPath:@"books.price"]);
    //获取所有图书的总价sum/平均价格avg/最大价格max/最小价格min
    NSLog(@"%@",[stu valueForKeyPath:@"books.@sum.price"]);
    //获取图书的总数
    NSLog(@"%@",[stu valueForKeyPath:@"books.@count"]);

 

IOS开发过程中的KVC机制

标签:

原文地址:http://www.cnblogs.com/CCMMBN/p/5336652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!