Skip to content
This repository
branch: master
Muhammad Hewedy September 29, 2011
file 251 lines (214 sloc) 8.143 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
//
// ObjectMapper.m
// ObjectMapper
//
// Created by Muhammad Hewedy mohammed_a_hewedy@hotmail.com on 9/25/11.
// Copyright 2011 . All rights reserved.
//
/*
Copyright 2011 Muhammad Hewedy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#import "ObjectMapper.h"

@implementation ObjectMapper

- (id)init
{
    self = [super init];
    if (self)
    {
        cachedPropertyList = [[NSMutableDictionary alloc]init];
    }
    return self;
}

-(id) initWithTypes: (NSDictionary*) _types
{
    self = [self init];
    if (self)
    {
        types = [_types retain];
    }
    return self;
}

-(void) objectFromDictionary: (NSDictionary*) dict object: (id) object
{
    NSString* objectId = [NSString stringWithFormat:@"%p", object];
    NSDictionary* propsDict = [cachedPropertyList objectForKey:objectId];
    
    if (propsDict == nil)
    {
        propsDict = [self getPropertiesOfClass:[object class]];
        [cachedPropertyList setValue:propsDict forKey:objectId];
    }
    
    for (id property in propsDict)
    {
        NSString* type = [propsDict objectForKey:property];
        id value = [dict objectForKey: property];
        
        if (value != nil && value != kCFNull/* For json null*/)
        {
            if ( [NSClassFromString(type) isSubclassOfClass:[NSString class]] ||
                [NSClassFromString(type) isSubclassOfClass:[NSNumber class]] )
            {
                [self set:object property:property value:value];
            
            }else if([NSClassFromString(type) isSubclassOfClass:[NSDictionary class]])
            {
                NSUInteger count = [value count];
                NSMutableDictionary* instanceDict = [[NSMutableDictionary alloc]initWithCapacity:count];
                [object performSelector:NSSelectorFromString([self getSetFunction:property]) withObject:instanceDict];
                NSString* dictType = [self getTypeforArrayProperty:object property:property];
                [self dictionaryFromDictionary:value object:instanceDict objectType:dictType];
                [instanceDict release];
            }else if([NSClassFromString(type) isSubclassOfClass:[NSArray class]])
            {
                NSUInteger count = [value count];
                NSMutableArray* instanceArrr = [[NSMutableArray alloc]initWithCapacity:count];
                [object performSelector:NSSelectorFromString([self getSetFunction:property]) withObject:instanceArrr];
                NSString* arrayType = [self getTypeforArrayProperty:object property:property];
                [self arrayFromArray:value object:instanceArrr objectType:arrayType];
                [instanceArrr release];
            }else // custom type (user objects)
            {
                id custObj = [[NSClassFromString(type) alloc]init];
                [object performSelector:NSSelectorFromString([self getSetFunction:property]) withObject:custObj];
                [self objectFromDictionary:value object:custObj];
                [custObj release];
            }
        }
        
    }
}

- (void)dealloc {
    [cachedPropertyList release];
    [types release];
    [super dealloc];
}

@end

@implementation ObjectMapper(private)

static const char *getPropertyType(objc_property_t property);

-(void) arrayFromArray: (NSArray*) value object: (NSMutableArray*) outArray objectType: (NSString*) type
{
    NSUInteger count = [value count];
    
    if (count > 0)
    {
        for (id currentValue in value)
        {
            id newObj = [[NSClassFromString(type) alloc] init];
            [self objectFromDictionary:currentValue object:newObj];
            [outArray addObject:newObj];
            [newObj release];
        }
    }
}

-(void) dictionaryFromDictionary: (NSDictionary*) value object: (NSMutableDictionary*) outDict objectType: (NSString*) type
{
    NSUInteger count = [value count];
    
    if (count > 0)
    {
        for (id property in value)
        {
            id newObj = [[NSClassFromString(type) alloc] init];
            id currentValue = [value objectForKey:property];
            [self objectFromDictionary:currentValue object:newObj];
            [outDict setObject:newObj forKey:property];
            [newObj release];
        }
    }
}

-(NSString*) getTypeforArrayProperty: (id) object property: (NSString*) property
{
    NSString* classProperty = [NSString stringWithFormat:@"%@.%@", [object class], property];
    
    NSString* type = [types objectForKey:classProperty];
    
    if (type)
        return type;
    else
    {
        type = [types objectForKey:property];
        if (type)
            return type;
        else
        {
            NSLog(@"Fetal error: type not found for property: %@", classProperty);
            return nil;
        }
    }
}

-(BOOL) set: (id) object property:(NSString*) property value:(id) value
{
    NSString* setter = [self getSetFunction:property];
    SEL setterSelector = NSSelectorFromString(setter);
    
    if ( [object respondsToSelector:setterSelector] )
    {
        [object performSelector: setterSelector withObject: value];
        return YES;
    }else
    {
        NSLog(@"object of type %@ doesn't responds to selector %@", [object class], setter);
        return NO;
    }
}

-(NSString*) getSetFunction: (NSString*) property
{
    NSString* setName = [NSString stringWithFormat: @"%@%@", [[property substringWithRange:NSMakeRange(0, 1)] capitalizedString],
                         [property substringFromIndex:1]];
    NSString* settterString = [NSString stringWithFormat:@"set%@:", setName];
    return settterString;
}

/**
* I am not the original auather of this method
*/
-(NSDictionary*) getPropertiesOfClass:(Class) clazz
{
    NSMutableDictionary* dict = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t* properties = class_copyPropertyList(clazz, &outCount);
    for(i = 0; i < outCount; i++)
    {
        objc_property_t _property = properties[i];
        const char *propName = property_getName(_property);
        if(propName)
        {
            const char *propType = getPropertyType(_property);
            NSString *propertyName = [NSString stringWithCString:propName encoding:NSUTF8StringEncoding];
            NSString *propertyType = [NSString stringWithCString:propType encoding:NSUTF8StringEncoding];
            [dict setValue:propertyType forKey:propertyName];
        }
    }
    free(properties);
    return dict;
}

/**
* I am not the original auather of this method
*/
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 && strlen(attribute) > 3 && attribute[0] == 'T')
        {
            NSUInteger i = strlen(attribute) - 4;
            //NSLog(@"attribute = %s, strlen = %lu, i=%lu",attribute, strlen(attribute), i);
            return (const char *)[[NSData dataWithBytes:(attribute + 3) length:i] bytes];
        }
    }
    return "@";
}

@end


@implementation NSDictionary (ObjectMapper)

-(void) toObject:(id) object withTypes: (NSDictionary*) types
{
    ObjectMapper* objectMapper = [[ObjectMapper alloc] initWithTypes:types];
    long double currTime = [[NSDate date] timeIntervalSince1970] * 1000 ;
    [objectMapper objectFromDictionary:self object:object];
    NSLog(@"parsing object %@ tooks %Lf ms", [object class], ([[NSDate date] timeIntervalSince1970] * 1000) - currTime);
    [objectMapper release];
}
@end



Something went wrong with that request. Please try again.