ios - Pattern for determining if object is fully or partially loaded -
the question not strictly tied ios, since encountered in ios app speak in terms of objective-c.
my ios app client, gets data server. data server json, , mapped classes. problem appears when server send necessary part of object.
lets full object is
{ "a" : 1, "b" : 2, "c" : 3 }
my class mapped is
@class myobject { int a, b, c; } @property (nonatomic) int a, b, c; -(id) initfromdictionary:(nsdictionary*)dict @end @implementation myobject -(id) initfromdictionary:(nsdictionary*)dict { self = [super init]; if (self) { = [dict[@"a"] intvalue]; b = [dict[@"b"] intvalue]; c = [dict[@"c"] intvalue]; } return self; } @end
the server can send
{ "a" : 1, "c" : 3 }
for request getaandc
,
{ "a" : 1, "b" : 2 }
for - getaandb
(these requests not dependent, thing similar object use). not need information b
in first 1 , c
in second one.
the problem following. when write code these requests surely know fields returned , not use empty field, after time may forget request returned partial object or full, , try use empty field. there can lot of errors, hard find.
is there practices case or maybe pattern determining if object or partially loaded , warning developer it?
you can implement :
@implementation myobject
-(id) initfromdictionary:(nsdictionary*)dict { self = [super init]; if (self) { = ([dict objectforkey: @"a"]) ? [[dict objectforkey: @"a"] intvalue] : 0; b = ([dict objectforkey: @"b"]) ? [[dict objectforkey: @"b"] intvalue] : 0; c = ([dict objectforkey: @"c"]) ? [[dict objectforkey: @"c"] intvalue] : 0;
// here can replace 0 nil in case if variable , b , c object type i.e. (id) type or can use default value here per convenience can track if partially or loaded
if ((a == 0) || (b == 0) || (c == 0)) { nslog(@"object partially loaded values : %d , b : %d , c : %d", a,b,c); }else{ nslog(@"object loaded values : %d , b : %d , c : %d", a,b,c); } } return self; } @end
or
@implementation myobject -(id) initfromdictionary:(nsdictionary*)dict { self = [super init]; if (self) { nsarray *keys = [dict allkeys]; for(nsstring * key in keys) { [self setvaluetoitsvariableforkey:key fromdictionary: dict]; } } return self; } - (void)setvaluetoitsvariableforkey:(nsstring *)key fromdictionary: (nsdictionary *)dict { switch ([key intvalue]) { case : = [[dict objectforkey: key] intvalue]; break; case : b b = [[dict objectforkey: key] intvalue]; break; case : c c = [[dict objectforkey: key] intvalue]; break; } } @end
Comments
Post a Comment