亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

objective-c如何實(shí)現(xiàn)java中的反射機(jī)制
PHPz
PHPz 2017-04-21 10:57:18
0
3
716

在開發(fā)iOS app時(shí),經(jīng)常會(huì)遇到服務(wù)端返回?cái)?shù)據(jù)不完整的情況,比如缺少key,或者value為null的情況。

java中可以定義一個(gè)類,用反射的機(jī)制來進(jìn)行數(shù)據(jù)初始化。

而objective-c中只能用nil和[NSNull null]來單獨(dú)判斷。來避免app crash。

整個(gè)view層也變得不夠純粹。

補(bǔ)充:
我現(xiàn)在的做法是。如果返回的是一個(gè)數(shù)組。數(shù)組中每一項(xiàng)又是一個(gè)對(duì)象。我們假設(shè)對(duì)象中有的key或者value是缺失的。那么就要遍歷一邊,逐個(gè)遇到不完整的情況追加key或者默認(rèn)值。這樣,在view層中,就不用再對(duì)key或value去做判斷了。代碼也專注在業(yè)務(wù)邏輯上。

問:
有沒有更好的。更優(yōu)雅的方式來實(shí)現(xiàn)。

PHPz
PHPz

學(xué)習(xí)是最好的投資!

reply all(3)
Ty80

I don’t quite understand what you mean. . . Java's reflection can dynamically obtain the method and attribute list of an instance. For this function, Obj-c can use NSObject's respondsToSelector: method to confirm whether an instance has a certain method; it can also use performSelector: to call the method. . Basically it can replace Java's reflection.
As for the problem of judging empty return value, I really don’t have a good way at the moment. I usually define a method and judge containsObject:, nil, [NSNull null], length or count in sequence. This method can be written in a util or can be extended and written in NSDictionary and NSArray.

伊謝爾倫

objc’s KVC mechanism is similar to java’s reflection. Please google it

For example
@interface A : NSObject{
NSString * name;
}

You can get it like this

A *a = [[A alloc] init];

NSString *name = [a objectForKey:@"name"];

I don’t know if you want this

You implement the nscoding interface. - (id)initWithCoder:(NSCoder *)aDecoder can do what you want. I don't know if I understand it correctly.

小葫蘆
  • OC has an open source framework of JSONModel, which can convert Json into ViewModel
  • The problem of null value can be determined when the View layer is used or the default value can be set when the ViewModel is constructed

  • Regarding reflection of OC, you can use NSClassFromString, NSSelectorFromString and other methods

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template