ios - Set Default values of NSString properties automatically -
i have many bean/data classes in code i'm using convert json network communication purposes. issue is, if there's nsstring
property in class want set default value empty string @"" rather nil. 1 option have :setting default values nsstring properties have write code set properties values, don't want this.
i tried getting properties using objc runtime , did this:
unsigned int numberofproperties = 0; objc_property_t *propertyarray = class_copypropertylist([self class], &numberofproperties); (nsuinteger = 0; < numberofproperties; i++) { objc_property_t property = propertyarray[i]; nsstring *name = [nsstring stringwithutf8string:property_getname(property)]; const char * propattr = property_getattributes(property); nsstring *propstring = [nsstring stringwithutf8string:propattr]; nsarray *attrarray = [propstring componentsseparatedbystring:@"\""]; if (attrarray.count > 0) { nsstring *proptype = [attrarray objectatindex:1]; if ([proptype containsstring:@"nsstring"]) { [self setvalue:@"" forkey:name]; } } } free(propertyarray);
this working charm me. issue have inherited classes , code sets values child class, doesn't sets values of properties in base class. i'm using xcode 6.3.1 & ios 8.x. appreciated. thanks
you may define recursive method setdefaultpropvaluesforclass:
in bean/data base class, e.g. bean
, , invoke base class init method. see implementation below:
@interface bean : nsobject // add props // ... // ..... @end @implementation bean - (instancetype)init { self = [super init]; if (self) { [self setdefaultpropvalues]; // todo: other initializations } return self; } - (void)setdefaultpropvalues { [self setdefaultpropvaluesforclass:self.class]; } - (void)setdefaultpropvaluesforclass:(class)refclass { if (![refclass issubclassofclass:[bean class]]) { return; } // first set default property values in super classes class baseclass = class_getsuperclass(refclass); [self setdefaultpropvaluesforclass:baseclass]; // unsigned int numberofproperties = 0; objc_property_t *propertyarray = class_copypropertylist(refclass, &numberofproperties); (nsuinteger = 0; < numberofproperties; i++) { objc_property_t property = propertyarray[i]; nsstring *name = [nsstring stringwithutf8string:property_getname(property)]; const char * propattr = property_getattributes(property); nsstring *propstring = [nsstring stringwithutf8string:propattr]; nsarray *allattrs = [propstring componentsseparatedbystring:@","]; // check if property readonly if (nsnotfound == [allattrs indexofobject:@"r"]) { // find property type token nsarray * attrarray = [propstring componentsseparatedbystring:@"\""]; if (attrarray.count > 1) { class proptype = nsclassfromstring([attrarray objectatindex:1]); if ([proptype issubclassofclass:[nsstring class]]) { [self setvalue:@"" forkey:name]; } } } } free(propertyarray); } @end
Comments
Post a Comment