Objective-c中的KVC、KVO

關於KVC(Key-Value-Coding鍵-值編碼的概念

     1、鍵-值編碼是一種用於間接訪問對象屬性的機制,使用該機制不需要調用setter、getter方法,和變量實例就可以訪問對象的屬性。

     2、鍵-值編碼方法在OC的非正式協議(類目)NSKeyCodingValue中被聲明,默認的實現方法有NSObject提供。

     3、鍵-值編碼支持帶有對象值的屬性,同時也支持純數值的類型和結構。非對象參數和返回類型會被識別並自動封裝/解封。

下面我們來用KVC(Key-Value-Coding)在沒有getter,setter方法的情況下訪問變量的屬性

如下,沒有setter、getter方法以及@property

.h文件

#import <Foundation/Foundation.h>

@interface Dog : NSObject{
    NSString *name;
}

@end

.m文件

#import "Dog.h"

@implementation Dog

@end
main文件

#import <Foundation/Foundation.h>
#import "Dog.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
   
        Dog *dog = [[Dog alloc]init];
        
        [dog setValue:@"娘希匹" forKey:@"name"];//設置鍵值對
        
        NSString *name = [dog valueForKey:@"name"];//根據鍵取值
        
        NSLog(@"The dog's name is ....%@...",name);
    }
    return 0;
}
打印結果:



2、看到上面的內容我們估計有個疑問,我們怎麼訪問屬性中的屬性呢,我們可以通過路徑的方式來訪問,同時我們也來看看純數值的情況

Dog類的.h文件

#import <Foundation/Foundation.h>
@class Tooth;

@interface Dog : NSObject{
    NSString *name;
    int age;
    Tooth *tooth;
}

@end
Dog類的.m文件

#import "Dog.h"

@implementation Dog

@end
Tooth類的.h文件

#import <Foundation/Foundation.h>

@interface Tooth : NSObject{
    
    int num;
    NSString *color;
}

@end
Tooth.m
#import "Tooth.h"

@implementation Tooth

@end

main文件

#import <Foundation/Foundation.h>
#import "Dog.h"
#import "Tooth.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        
        Dog *dog = [[Dog alloc]init];
        
        [dog setValue:@"娘希匹" forKeyPath:@"name"];
        [dog setValue:@5 forKeyPath:@"age"];

        NSString *name = [dog valueForKey:@"name"];
        NSNumber *age = [dog valueForKey:@"age"];

        NSLog(@"The dog's name is ....%@...",name);
        NSLog(@"%@",age);
        
        
        Tooth *tooth = [[Tooth alloc]init];
        
        [tooth setValue:@10 forKey:@"num"];
        [tooth setValue:@"black" forKey:@"color"];
        [dog setValue:tooth forKey:@"tooth"];
        
        NSNumber *toothNum  = [dog valueForKeyPath:@"tooth.num"];
        NSString *toothColor = [dog valueForKeyPath:@"tooth.color"];
        
        NSLog(@"The dog's teeth num is %@,color is %@",toothNum,toothColor);
        
        
        //下面我們使用路徑的方式
        [dog setValue:@12 forKeyPath:@"tooth.num"];
        [dog setValue:@"white" forKeyPath:@"tooth.color"];
        
        NSNumber *toothNum1  = [dog valueForKeyPath:@"tooth.num"];
        NSString *toothColor1 = [dog valueForKeyPath:@"tooth.color"];
        
        NSLog(@"The dog's teeth num is %@,color is %@",toothNum1,toothColor1);
        
        [tooth release];
        [dog release]; 
    }
    return 0;
}

打印結果:



二、KVO(Key Value Observing)鍵值觀察

鍵值觀察是一種使對象獲取其他對象的特定屬性變化的通知機制。

KVO主要用於視圖交互方面,比如界面的某些數據變化了,界面的顯示也跟着需要變化,那就要建立數據和界面的關聯


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章