Skip to content

Instantly share code, notes, and snippets.

@jgrana
Created November 14, 2014 20:56
Show Gist options
  • Save jgrana/3d3c69dad0a97e8291a6 to your computer and use it in GitHub Desktop.
Save jgrana/3d3c69dad0a97e8291a6 to your computer and use it in GitHub Desktop.
Iterate properties snippet
const char *property_getTypeString( objc_property_t property ) {
const char * attrs = property_getAttributes( property );
if ( attrs == NULL )
return ( NULL );
static char buffer[256];
const char * e = strchr( attrs, ',' );
if ( e == NULL )
return ( NULL );
int len = (int)(e - attrs);
memcpy( buffer, attrs, len );
buffer[len] = '\0';
return ( buffer );
}
/**
* Validate Properties iterates overall all the properties of the given object and ensures that all
* populated values are the correct property type and are not null
*/
- (void)validateProperties:(id)object {
Class cls = [object class];
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(cls, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
fprintf(stdout, "%s %s\n", property_getName(property), property_getTypeString(property));
NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
NSString *propertyType = [NSString stringWithUTF8String:property_getTypeString(property)];
propertyType = [propertyType substringWithRange:NSMakeRange(3, propertyType.length - 4)];
id value = [object valueForKey:propertyName];
Class foundClass = NSClassFromString(propertyType);
XCTAssertTrue([value isKindOfClass:foundClass],
@"Expected value of %@ to be of type %@, but found %@!", propertyName, propertyType,
NSStringFromClass([value class]));
}
free(properties);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment