用字典給Model賦值

2021-09-06 18:01:09 字數 3193 閱讀 8854

用字典給model賦值

此篇教程講述通過runtime擴充套件nsobject,可以直接用字典給model賦值,這是相當有用的技術呢。

原始碼:nsobject+properties.h 與 nsobject+properties.m

//

//nsobject+properties.h

////

created by youxianming on 14-9-4.

////

#import

@inte***ce

nsobject (properties)

- (void)setdatadictionary:(nsdictionary*)datadictionary;

- (nsdictionary *)datadictionary;

@end

//

//nsobject+properties.m

////

created by youxianming on 14-9-4.

////

#import

"nsobject+properties.h

"#import

@implementation

nsobject (properties)

#pragma public - 公開方法

- (void)setdatadictionary:(nsdictionary*)datadictionary

- (nsdictionary *)datadictionary

#pragma private - 私有方法

//通過屬性名字拼湊setter方法

- (sel)getsetterselwithattibutename:(nsstring*)attributename

//通過字典設定屬性值

- (void)setattributes:(nsdictionary*)datadic obj:(id

)obj

else

//執行setter方法

[obj performselectoronmainthread:sel

withobject:value

waituntildone:[nsthread ismainthread]];

}}}//

獲取乙個類的屬性名字列表

- (nsarray*)propertynames:(class)class

free(properties);

return

propertynames;}//

根據屬性陣列獲取該屬性的值

- (nsdictionary*)propertiesandvaluesdictionary:(id)obj properties:(nsarray *)properties

propertiesvaluesdic[property] =valueobj;}}

return

propertiesvaluesdic;

}@end

測試用model

model.h 與 model.m

//

//runtime

////

created by youxianming on 14-9-5.

////

#import

@inte***ce

model : nsobject

@property (nonatomic, strong) nsstring *name;

@property (nonatomic, strong) nsnumber *age;

@property (nonatomic, strong) nsdictionary *addressinfo;

@property (nonatomic, strong) nsarray *events;

@end

//

//runtime

////

created by youxianming on 14-9-5.

////

#import

"model.h

"@implementation

model

@end

使用時的情形

//

////

runtime

////

created by youxianming on 14-9-5.

////

#import""

#import

"nsobject+properties.h

"#import

"model.h

"@implementation

,

@"events

" : @[@"

one", @"

two", @"

three

"]};

//列印出屬性值

nslog(@"%@"

, model.datadictionary);

return

yes;

}@end

列印的資訊:

2014-09-05 21:03:54.840 runtime[553:60b] ;

age = 26;

events =     (

one,

two,

three

);

name = youxianming;

}以下是兩段核心**(符合單一職能):

用字典給Model賦值

用字典給model賦值 此篇教程講述通過runtime擴充套件nsobject,可以直接用字典給model賦值,這是相當有用的技術呢。原始碼 nsobject properties.h 與 nsobject properties.m nsobject properties.h created by ...

不能用字串給字元陣列賦值

c和指標 pointers on c 8.1.11 乙個字串,如 hello 一般為字串常量,可以用它對字元指標賦值,或初始化,相當於把這個字串常量的首位址賦給這個指標,如 char p hello 或者 char p p hello 但是,當用 hello 給字元陣列作初始化時,hello 並非乙...

iOS JSON字典轉模型model

ios開發中,經常會用到字典轉模型,咱們平常常用的是mjexstend框架,該框架功能完善,但是在咱們用的時候基本上只是在資料解析的時候會用到json字典轉模型,僅此乙個功能,你們龐大的一套框架,是不是有些浪費啦,所以咱們自己寫乙個小的分類,運用一點點知識點就可以搞定,下面直接上 該分類有三個功能 ...