Skip to content

Instantly share code, notes, and snippets.

@zekunyan
Last active August 29, 2015 14:24
Show Gist options
  • Save zekunyan/7054a326eb2e0386d69a to your computer and use it in GitHub Desktop.
Save zekunyan/7054a326eb2e0386d69a to your computer and use it in GitHub Desktop.
Runtime set init value.
/*
// DEMO
int main(int argc, const char *argv[]) {
@autoreleasepool {
// JSON到Entity
UserEntity *userEntity = [UserEntity new];
// 检查属性,设置默认值。
checkEntity(userEntity);
NSLog(@"%@", userEntity);
}
return 0;
}
*/
/**
* 解析Property的Attributed字符串
*/
static const char *getPropertyType(objc_property_t property) {
const char *attributes = property_getAttributes(property);
char buffer[1 + strlen(attributes)];
strcpy(buffer, attributes);
char *state = buffer, *attribute;
while ((attribute = strsep(&state, ",")) != NULL) {
if (attribute[0] == 'T' && attribute[1] != '@') {
// 利用NSData复制一份字符串
return (const char *) [[NSData dataWithBytes:(attribute + 1) length:strlen(attribute) - 1] bytes];
} else if (attribute[0] == 'T' && attribute[1] == '@' && strlen(attribute) == 2) {
return "id";
} else if (attribute[0] == 'T' && attribute[1] == '@') {
return (const char *) [[NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] bytes];
}
}
return "";
}
/**
* 给对象的属性设置默认值
*/
void checkEntity(NSObject *object) {
// 类型常量
static const char *CLASS_NAME_NSSTRING;
static const char *CLASS_NAME_NSNUMBER;
static const char *CLASS_NAME_NSARRAY;
// 初始化类型常量
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
CLASS_NAME_NSSTRING = NSStringFromClass([NSString class]).UTF8String;
CLASS_NAME_NSNUMBER = NSStringFromClass([NSNumber class]).UTF8String;
CLASS_NAME_NSARRAY = NSStringFromClass([NSArray class]).UTF8String;
});
@try {
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList([object class], &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
id propertyValue = [object valueForKey:propertyName];
// 值为空,才设置默认值
if (!propertyValue) {
// NSString
if (strncmp(CLASS_NAME_NSSTRING, getPropertyType(property), strlen(CLASS_NAME_NSSTRING)) == 0) {
[object setValue:@"str" forKey:propertyName];
}
// NSNumber
if (strncmp(CLASS_NAME_NSNUMBER, getPropertyType(property), strlen(CLASS_NAME_NSNUMBER)) == 0) {
[object setValue:@100 forKey:propertyName];
}
// NSArray
if (strncmp(CLASS_NAME_NSARRAY, getPropertyType(property), strlen(CLASS_NAME_NSARRAY)) == 0) {
[object setValue:@[@"item"] forKey:propertyName];
}
}
}
free(properties);
} @catch (NSException *exception) {
NSLog(@"Check Entity Exception: %@", [exception description]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment