在开发iOS app时,经常会遇到服务端返回数据不完整的情况,比如缺少key,或者value为null的情况。
java中可以定义一个类,用反射的机制来进行数据初始化。
而objective-c中只能用nil和[NSNull null]来单独判断。来避免app crash。
整个view层也变得不够纯粹。
补充:
我现在的做法是。如果返回的是一个数组。数组中每一项又是一个对象。我们假设对象中有的key或者value是缺失的。那么就要遍历一边,逐个遇到不完整的情况追加key或者默认值。这样,在view层中,就不用再对key或value去做判断了。代码也专注在业务逻辑上。
问:
有没有更好的。更优雅的方式来实现。
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