Objective-C Tips & Trick - Prioregroup.com
[Objective-C] Copy object with property values
       
back

//  Created by Danilo Priore on 02/04/12.
//  Copyright (c) 2011 Prioregroup.com. All rights reserved.
//
//  Copy object with property values
//
- (id)copy {
    
 	id copied = [[[self class] alloc] init];
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    for (int i = 0; i < count; ++i) {
        objc_property_t property = properties[i];
        NSString *propertyAttributes = [[[NSString alloc] initWithUTF8String:property_getAttributes(property)] autorelease];
        NSArray *propertyAttributeArray = [propertyAttributes componentsSeparatedByString:@","];
        BOOL isReadOnly = NO;
        
        for (NSString *string in propertyAttributeArray) {
            isReadOnly = isReadOnly || [string isEqual:@"R"];
        }

        if (!isReadOnly) {
            NSString *name = [NSString stringWithCString:property_getName(properties[i]) encoding:NSUTF8StringEncoding];
                [copied setValue:[self valueForKey:name] forKey:name];
        }
    }
    free(properties);
    
	return [copied autorelease];
}






Copyright © 1996-2018 Centro Studi Informatica di Danilo Priore. All rights reserved. P.I.10149810581.
prioregroup.com