iOS學習之KVC原理,ioskvc原理

來源:互聯網
上載者:User

iOS學習之KVC原理,ioskvc原理
1. KVC的實現原理

  • 遍曆字典裡面所有的key,以name為例
  •  去模型中尋找有沒有setName:方法,有就直接調用賦值

  •  假如沒有找到setName:方法,就會繼續尋找有沒有_name屬性,有就_name = value賦值

  •  假如沒有找到_name,還會繼續尋找模型中有沒有name屬性

  •  最終沒有找到,就會直接報錯

  報錯資訊:

 KVC主要用於model的賦值,model最好定義我們想要的屬性,但是有時會和我們得到的資料有一些不同,以下是幾種常見情況:

  • 當我們取到的資料多於model的屬性時,根據KVC原理就會出現上述的錯誤,解決辦法:在model的.m檔案中重寫setValue:forUndefinedKey:方法
#import "ZFFlag.h"@implementation ZFFlag- (void)setValue:(id)value forUndefinedKey:(NSString *)key{    }@end
  • 當我們需要的屬性的類型和得到的資料的類型不同,解決辦法:重寫屬性的setter方法(根據KVC的尋找順序可知)

  假如在視圖中需要一張圖片,但是得到的資料中一般是圖片名,也就是一個 NSString * 類型的資料,具體解決辦法請看代碼

#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>@interface ZFFlag : NSObject@property (nonatomic, strong) NSString *name;@property (nonatomic, strong) UIImage *icon;// 重寫icon的setter方法,注意類型為得到的資料中該屬性的類型- (void)setIcon:(NSString *)icon{    _icon = [UIImage imageNamed:icon];}// 防崩- (void)setValue:(id)value forUndefinedKey:(NSString *)key{    }@end
#import "ZFFlagView.h"#import "ZFFlag.h"@interface ZFFlagView ()@property (weak, nonatomic) IBOutlet UILabel *label;@property (weak, nonatomic) IBOutlet UIImageView *imageView;@end@implementation ZFFlagView- (void)setFlag:(ZFFlag *)flag{    _flag = flag;        // 給子控制項賦值    _label.text = flag.name;    _imageView.image = flag.icon;}@end

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.