IOS開發過程中的KVC機制

來源:互聯網
上載者:User

標籤:

作用:提供了另一種  為對象的屬性賦值及讀取對象屬性的編寫代碼的方式

—————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:@"[email protected]"]);
    //擷取圖書的總數
    NSLog(@"%@",[stu valueForKeyPath:@"[email protected]"]);

 

IOS開發過程中的KVC機制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.