6.ios之字典與模型

來源:互聯網
上載者:User

標籤:

1.用模型取代字典的好處


?使用字典的壞處

?一般情況下,設定資料和取出資料都使用“字串類型的key”,編寫這些key時,編譯器不會有任何友善提示,需要手敲

dict[@"name"] =@"Jack";

NSString*name = dict[@"name"];

?手敲字串key,key容易寫錯?Key如果寫錯了,編譯器不會有任何警告和報錯,造成設錯資料或者取錯資料??使用模型的好處?所謂模型,其實就是資料模型,專門用來存放資料的對象,用它來表示資料會更加專業?模型設定資料和取出資料都是通過它的屬性,屬性名稱如果寫錯了,編譯器會馬上報錯,因此,保證了資料的正確性?使用模型訪問屬性時,編譯器會提供一系列的提示,提高編碼效率

app.name = @"Jack”;

NSString*name = app.name;


2.字典轉模型


?字典轉模型的過程最好封裝在模型內部??模型應該提供一個可以傳入字典參數的構造方法?- (instancetype)initWithDict:(NSDictionary*)dict;?+ (instancetype)xxxWithDict:(NSDictionary*)dict;

3.instancetype

?instancetype在類型表示上,跟id一樣,可以表示任何物件類型??instancetype只能用在返回值類型上,不能像id一樣用在參數類型上??instancetype比id多一個好處:編譯器會檢測instancetype的真實類型

4.字典轉模型的過程





5.Sample


#import<Foundation/Foundation.h>@interface MJApp :NSObject-(NSString*)GetName;-(NSString*)GetIcon;-(instancetype) initWithDict:(NSDictionary *) dict;+(instancetype) appWithDict:(NSDictionary *) dict;@end#import "MJApp.h"@interface MJApp()    @property (nonatomic,copy) NSString *name;    @property (nonatomic,copy) NSString *icon;@end@implementation MJApp-(NSString*)GetName{    return self.name;}-(NSString*)GetIcon{    return self.icon;}-(instancetype) initWithDict:(NSDictionary *)dict{    if (self = [super init]) {        self.name = dict[@"name"];        self.icon = dict[@"icon"];    }    return self;}+(instancetype)appWithDict:(NSDictionary *)dict{    return [[self alloc] initWithDict:dict];}@end




6.ios之字典與模型

聯繫我們

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