Last Updated: February 25, 2016
·
2.336K
· nebiros

Loop through ObjC properties to serialize an object

Woot.h

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface Woot : NSObject <NSCoding>

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *address;
@property (strong, nonatomic) NSString *phone;

- (id)initWithCoder:(NSCoder *)aDecoder;
- (void)encodeWithCoder:(NSCoder *)aCoder;

@end

Woot.m

#import "Woot.h"

@implementation Woot

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        unsigned int outCount, i;
        objc_property_t *properties = class_copyPropertyList([self class], &outCount);
        for (i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];
            NSString *p = [NSString stringWithFormat:@"%s", property_getName(property)];
            [self setValue:[aDecoder decodeObjectForKey:p] forKey:p];
        }

        free(properties);
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *p = [NSString stringWithFormat:@"%s", property_getName(property)];
        [aCoder encodeObject:[self valueForKey:p] forKey:p];
    }

    free(properties);
}

@end