在開發(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)。
學(xué)習(xí)是最好的投資!
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.
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