Skip to content

Instantly share code, notes, and snippets.

@buh
Last active August 29, 2015 13:57
Show Gist options
  • Save buh/9809833 to your computer and use it in GitHub Desktop.
Save buh/9809833 to your computer and use it in GitHub Desktop.
Helper for JSON encode/decode custom class properties
//
// NSObject+CSProperties.h
// Cheapshot
//
// Created by Alexey Bukhtin on 17.02.14.
// Copyright (c) 2014 Cheapshot. All rights reserved.
//
@interface NSObject (CSProperties)
- (NSArray *)classPropertyNames;
- (NSDictionary *)classPropertyValues;
- (NSDictionary *)classPropertyValuesExcludePropertyNames:(NSArray *)excludePropertyNames;
- (void)populateClassPropertiesWithData:(NSDictionary *)data;
@end
//
// NSObject+CSProperties.m
// Cheapshot
//
// Created by Alexey Bukhtin on 17.02.14.
// Copyright (c) 2014 Cheapshot. All rights reserved.
//
#import <objc/runtime.h>
#import "NSObject+CSProperties.h"
@implementation NSObject (CSProperties)
- (NSArray *)classPropertyNames
{
NSMutableArray *propertyNames = [NSMutableArray array];
objc_property_t *properties = class_copyPropertyList([self class], NULL);
for (objc_property_t *cursor = properties; *cursor != NULL; cursor++) {
const char *property = property_getName(*cursor);
if (property) {
NSString *propertyName = [NSString stringWithCString:property encoding:[NSString defaultCStringEncoding]];
[propertyNames addObject:propertyName];
}
}
free(properties);
return [propertyNames copy];
}
- (NSDictionary *)classPropertyValues
{
return [self classPropertyValuesExcludePropertyNames:nil];
}
- (NSDictionary *)classPropertyValuesExcludePropertyNames:(NSArray *)excludePropertyNames
{
NSMutableDictionary *classPropertyValues = [NSMutableDictionary dictionary];
NSArray *classPropertyNames = [self classPropertyNames];
[classPropertyNames enumerateObjectsUsingBlock:^(NSString *propertyName, NSUInteger idx, BOOL *stop) {
if (!excludePropertyNames || ![excludePropertyNames containsObject:propertyName]) {
id value = [self valueForKey:propertyName];
if (value) {
classPropertyValues[propertyName] = value;
}
}
}];
return [classPropertyValues copy];
}
- (void)populateClassPropertiesWithData:(NSDictionary *)data
{
if (data && [data isKindOfClass:[NSDictionary class]] && data.count) {
[data enumerateKeysAndObjectsUsingBlock:^(NSString *propertyName, id value, BOOL *stop) {
if ([self respondsToSelector:NSSelectorFromString(propertyName)]) {
[self setValue:value forKey:propertyName];
}
}];
}
}
@end
@buh
Copy link
Author

buh commented Mar 27, 2014

TODO: NSDate value encode/decode and etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment