/**
* 遍历整个类的属性,将类型为‘nsstring’类型的属性初始化为‘’;用以防止未初始化使用时null造成的崩溃
*/
- (void)initStringProperty {
//对象属性的个数
unsigned int propertyCount = 0;
//通过运行时获取当前类的属性
objc_property_t *propertys = class_copyPropertyList([self class], &propertyCount);
//把属性放入数组中
for (int i = 0; i < propertyCount; i++) {
//取出第一个属性
objc_property_t property = propertys[i];
//获取属性名称
const char * propertyName = property_getName(property);
//获取属性类型字符串
const char * propertyTypeString = property_getAttributes(property);
unsigned int propertyTypeCount = 0;
objc_property_attribute_t *propertysType = property_copyAttributeList(property, &propertyTypeCount);
for (int i = 0; i < propertyTypeCount; i++) {
const char * typeName = propertysType[i].name;
const char * typeValue = propertysType[i].value;
DLog(@"--属性类型名称:%s --属性类型值:%s", typeName, typeValue);
}
free(propertysType);
const char * propertyTypeValue = property_copyAttributeValue(property, [@"T" cStringUsingEncoding:NSASCIIStringEncoding]);
DLog(@"--属性名称:%s--属性类型字符串 %s ", propertyName, propertyTypeString);
DLog(@"**类属性最终类型值为 %s 如果为NSString 我们进行初始化@“” 操作 ^_^ \r\n", propertyTypeValue);
if ([[NSString stringWithFormat:@"%s", propertyTypeValue] containsString:@"NSString"]) {
//通过creatSetterWithPropertyName获取实体类属性的set方法
SEL setSel = [self creatSetterWithPropertyName:[NSString stringWithFormat:@"%s", propertyName]];
if ([self respondsToSelector:setSel]) {
//把初始值通过setter方法赋值给实体类属性
[self performSelectorOnMainThread:setSel
withObject:@""
waitUntilDone:[NSThread isMainThread]];
}
}
}
free(propertys);
}
/**
* 通过nsstring返回对应的属性的set方法
*
* @param peropertyName 属性名称
*
* @return 对应的set方法名称
*/
- (SEL)creatSetterWithPropertyName:(NSString *)peropertyName{
//1.0首字母大写 (该方法注释原因为,获取的会将字符串首个字母大写,其余全部小写,导致获取不准set方法)
//peropertyName = peropertyName.capitalizedString;
peropertyName = [peropertyName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[peropertyName substringToIndex:1] uppercaseString]];
//2.0拼接set关键字
peropertyName = [NSString stringWithFormat:@"set%@:", peropertyName];
//3.0返回set方法
return NSSelectorFromString(peropertyName);
}
转载于:https://my.oschina.net/ichinadev/blog/610647