ios - How to get all elements returned by a method include those defined from super class? -


i'm writing json <> model serializer. 1 of feature ignore properties model when converting json. i'm letting model implement - (nsarray *)ignoreproperties method tell serializer properties should ignore. needs support inheritance. i'm stuck how combine array elements object , super classes.

@protocol serializermapping <nsobject> - (nsarray *)ignoreproperties; @end  @interface basemodel : nsobject <serializermapping> @property nsstring *baseproperty; @end  @implementation basemodel - (nsarray *)ignoreproperties {     return nil; // nothing ignore } @end  // --- @interface supermodel : basemodel @property nsstring *property1; @property nsstring *property2; @end  @implementation supermodel - (nsarray *)ignoreproperties {     return @[@"property1"]; } @end  // --- @interface awesomemodel : supermodel @property nsstring *property3; @property nsstring *property4; @end  @implementation awesomemodel - (nsarray *)ignoreproperties {     return @[@"property3"]; } @end  // --- serializer awesomemodel *obj = [awesomemodel new]; nsarray *blacklist = [obj ignoreproperties]; // returns "property3" 

obviously above code doesn't work how can implement ignoreproperties so, return property1 , property3?

very bad way:

@implementation awesomemodel - (nsarray *)ignoreproperties {     return [[super ignoreproperties] arraybyaddingobjectsfromarray:@[@"property3"]]; } @end 

a lot of potential bugs. if subclass forgets invoking super chain broken. or basemodel return nil code wouldn't work @ all.

i think teamnorge on right track code won't work posted, though, since array isn't mutable.

make property mutable array. have base class create it init's init method:

in base class header:

@property (nonatomic, retain) nsmutablearray *ignoreproperties; 

then in init base class:

-(instancetype) init; {   self = [super init];   if (!self)     return nil;   self.ignoreproperties =  [@[@"property1"] mutablecopy]; } 

and in init subclass:

-(instancetype) init; {   self = [super init];   if (!self)     return nil;   [self.ignoreproperties  addobject: @"property2"];   //or add multiple objects...   nsarray *newproperties = @[@"property2", @"property3"];   [self.ignoreproperties  addobjectsfromarray: newproperties]; } 

for efficiency's sake, might better make array immutable , have subclass's init method replace array created using arraybyaddingobject or arraybyaddingobjectsfromarray. (immutable objects less costly system mutable forms. in case array of properties created once @ initialization of class, , persist it's lifetime.)


Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -