ios - Instantiate subclass from mother class intelligently -
let's have motheclass (abstract or not) item , 2 subclasses itema et itemb both inherit item
all instances created based on nsdictionary through next method
-(id)initwithjson:(nsdictionary *)d{ //first instantiate mutual properties motherclass if ([super initwithjson:d]){ //do specific stuff subclass } homecoming self; } now let's fetch webservice array can contain both itema & item created.
currently utilize if/then status determine subclass instantiate based on dictionary content, instance :
[(nsarray*)data enumerateobjectsusingblock:^(id obj, nsuinteger idx, bool *stop) { if ([obj[@"kind"] isequaltostring:@"a"]) [interactions addobject:[[itema alloc] initwithjson:obj]]; else if ([obj[@"kind"] isequaltostring:@"b"]) [interactions addobject:[[itemb alloc] initwithjson:obj]]; else [interactions addobject:[[item alloc] initwithjson:obj]]; }]; now point next : there way have 1 line of code - default - instantiate item object, , based on kind itema or itemb in other words, can write code in init method of motherclass item instantiate subclass instead if conditions fulfilled in nsdictionary parameters parsed ?
thanks
in mother class, add together convenience method this:
+(instancetype)itemwithjson:(nsdictionary *)obj { id item; if ([obj[@"kind"] isequaltostring:@"a"]) { item = [[itema alloc] initwithjson:obj]; } else if ([obj[@"kind"] isequaltostring:@"b"]) { item = [[itemb alloc] initwithjson:obj]; } else { item = [[item alloc] initwithjson:obj]; } homecoming item; } then utilize this:
[(nsarray*)data enumerateobjectsusingblock:^(id obj, nsuinteger idx, bool *stop) { [interactions addobject:[item itemwithjson:obj]]; }]; ios objective-c class inheritance initialization
No comments:
Post a Comment