iOS的設計模式-KVC

來源:互聯網
上載者:User

標籤:

      關於iOS的設計模式,相信大家肯定不會陌生了,其中最常見的是MVC,也就是模型-視圖-控制器模式,也是我們經常用的,這個這裡就不在敘述了,這裡主要講一講KVC這種模式,若文中有紕漏,請廣大博友出來指正~~

聊聊設計模式

     雖然設計模式時時刻刻存在我們的項目工程裡,但是我們卻很少去注意它們,只是不自覺的去運用。

     在軟體設計領域,設計模式是對通用問題的可複用的解決方案。設計模式是一系列幫你寫出更可理解和複用代碼的模板,設計模式幫你建立松耦合的代碼以便你不需要費多大力就可以改變或者替換代碼中的組件。

     所以多知道一些設計模式有助於我們的代碼更加規範,清晰。使我們的代碼風格更加好。

深扒一下KVC     

     KVC 全稱 key valued coding 索引值編碼

     反射機制是在運行狀態中,對於任意一個類,都能夠知道這個類的所有屬性和方法;對於任意一個對象,都能夠調用它的任意一個方法和屬性.JAVA,C#都有這個機制。ObjC也有,所以你根部不必進行任何操作就可以進行屬性的動態讀寫,就是KVC。

     KVC的操作方法由NSKeyValueCoding提供,而他是NSObject的類別,也就是說ObjC中幾乎所有的對象都支援KVC操作。

Person.h

@interface Person : NSObject{    int weight;}@property(nonatomic,readonly,copy) NSString *name;@property(nonatomic,readonly, assign) int age;@property(nonatomic,strong) Dog * dog;@property(nonatomic,assign) id ID;-(instancetype)initWithDict:(NSDictionary *)dict;@end

Person.m

@implementation Person{    int _height;}-(instancetype)initWithDict:(NSDictionary *)dict{    if (self=[super init])    {        //字典轉模型的常用語句        [self setValuesForKeysWithDictionary:dict];    }    return self;}//當key的值是沒有定義時,設定會執行的方法- (void)setValue:(id)value forUndefinedKey:(NSString *)key {        if ([key isEqualToString:@"id"])    {        self.ID = value;    }}//當key的值是沒有定義時,取值時執行的方法- (id)valueForUndefinedKey:(NSString *)key {            if ([key isEqualToString:@"id"]) {        return self.ID;    }    return [NSNull null];}

main.m

Person * p1 = [[Person alloc]init];Dog * d1 = [[Dog alloc] init];p1.dog = d1;   //setValue:屬性值 forKey:屬性名稱(用於簡單路徑)  //使用KVC間接修改對象屬性時,系統會自動判斷對象屬性的類型,並完成轉換。如該程式中的“170”.      [p1 setValue:@"170" forKey:@"height"];[p1 setValue:@"70" forKey:@"weight"];[p1 setValue:@"1" forKey:@"id"];//setValue:屬性值 forKeyPath:屬性路徑(用於複合路徑)//用KVC取一個嵌套層次很深的路徑的時候,只要給它一個路徑就能把想要的屬性給拿出來。(.可以理解為路徑。一直一直進入)。能夠協助我們很方便的編碼。[p1 setValue:@"dahuan" forKeyPath:@"dog.name"];//valueForKey:屬性名稱 、valueForKeyPath:屬性名稱(用於複合路徑)NSLog(@"height = %d weight = %d id = %@ dog.name = %@" ,[[p1 valueForKey:@"height"] intValue],[[p1 valueForKey:@"weight"] intValue],[p1 valueForKey:@"id"],[p1 valueForKeyPath:@"dog.name"]);log日誌:height = 170 weight = 70 id = 11111 dog.name = dahuan所有的屬性都可以賦值成功NSDictionary * dict = @{@"height":@"160",                        @"weight":@"60",                        @"id":@"11101"                        };        Person * p2 = [[Person alloc] initWithDict:dict];NSLog(@"height = %d weight = %d id = %@",[[p2 valueForKey:@"height"] intValue],[[p2 valueForKey:@"weight"] intValue],[p2 valueForKey:@"id"]);log日誌:height = 160 weight = 60 id = 11101所有的屬性都可以賦值成功
KVC尋找屬性的順序
  1. 用@property定義的屬性的key值
  2. setter方法的key值
  3. 直接存取成員變數,先找key,如果找不到,再找_key
  4. 以上三種都未找到就會調用- (void)setValue:(id)value forUndefinedKey:(NSString *)key 方法。
  5. 如果沒有重寫setValue:forUndefinedKey程式會馬上崩潰。

注意:KVC可以訪問成員變數,無論是否提供getter/setter方法,無論可見度是怎樣,是否有readonly修飾。

setValue:forUndefinedKey與valueForUndefinedKey的應用

KVC的主要用途無非是ORM映射,就是將dictionary轉換成model,但有些伺服器返回的欄位有可能是oc的關鍵字比如‘id’,’description’等。如上代碼舉得id的例子,我們無法讓@property後面key值為id,於是使用大寫的ID代替,KVC是區分大小寫我們不用擔心。這時我們只需在setValue:forUndefinedKey把id的key值賦值給ID的key值,就可以避免關鍵字的尷尬。

KVC底層實現
比如說如下的一行KVC的代碼: [person setValue:@"dahuan" forKey:@"name"]; 就會被編譯器處理成: SEL sel = sel_get_uid ("setValue:forKey:");IMP method = objc_msg_lookup (person->isa,sel);method(person, sel, @"dahuan", @"name");
KVC與runtime應用
#import "MyModel.h"#import <objc/runtime.h> @implementation MyModel //解檔- (id)initWithCoder:(NSCoder *)decoder{    if (self = [super init]) {        unsigned int count = 0;        //擷取類中所有成員變數名        Ivar *ivar = class_copyIvarList([MyModel class], &count);        for (int i = 0; i<count; i++) {            Ivar iva = ivar[i];            const char *name = ivar_getName(iva);            NSString *strName = [NSString stringWithUTF8String:name];            //進行解檔取值            id value = [decoder decodeObjectForKey:strName];            //利用KVC對屬性賦值            [self setValue:value forKey:strName];        }        free(ivar);    }    return self;}//歸檔- (void)encodeWithCoder:(NSCoder *)encoder{    unsigned int count;    Ivar *ivar = class_copyIvarList([MyModel class], &count);    for (int i=0; i<count; i++) {        Ivar iv = ivar[i];        const char *name = ivar_getName(iv);        NSString *strName = [NSString stringWithUTF8String:name];        //利用KVC取值        id value = [self valueForKey:strName];        [encoder encodeObject:value forKey:strName];    }    free(ivar);}@end
NSArray/NSSet等都支援KVC
Person * p1 = [[Person alloc]init];Dog * d1 = [[Dog alloc] init];d1.name = @"iPhone";p1.dog = d1;        Person * p2 = [[Person alloc]init];Dog * d2 = [[Dog alloc] init];d2.name = @"ios";p2.dog = d2;NSArray *persons=@[p1,p2];   NSArray *arrayM=[persons valueForKeyPath:@"dog.name"];NSLog(@"%@",arrayM);log日誌:(    iPhone,    ios)
KVC的逆向使用
Person * p1 = [[Person alloc]init];[p1 setValue:@"170" forKey:@"height"];[p1 setValue:@"70" forKey:@"weight"];[p1 setValue:@"11111" forKey:@"id"];        NSArray * arr = @[@"height",@"weight",@"id"];NSDictionary * dict = [p1 dictionaryWithValuesForKeys:arr];NSLog(@"%@",dict);log日誌:{    height = 170;    id = 11111;    weight = 70;}

最後附蘋果KVC官方文檔:

https://developer.apple.com/library/mac/documentation/General/Conceptual/DevPedia-CocoaCore/KeyValueCoding.html

 

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.