Override all setters and getters of a subclass

Viewed 1134

I want to override the setter and getter and find the class of an objc_property_t without doing it individually for each property.

I get all the properties like so:

unsigned int numberOfProperties;
    objc_property_t *propertyArray = class_copyPropertyList([self class], &numberOfProperties);
    for (NSUInteger i = 0; i < numberOfProperties; i++) {
        objc_property_t property = propertyArray[i];
        NSString *name = [[NSString alloc] initWithUTF8String:property_getName(property)];

        property.getter = SEL; //?
    }

This is an example of how I want to override the getter and setter - if there is a better way, let me know. NSInvocation maybe?

- (UIImage *)backgroundImage
{
    return [self overrideGetterWithSelector:NSStringFromSelector(_cmd)];
}

- (void)setBackgroundImage:(UIImage *)backgroundImage
{
    [self overrideSetterForObject:backgroundImage forSelector:NSStringFromSelector(_cmd)];
}

Or is there a way to intercept all messages sent to a class?

My goal is to make a generic way to store properties of a class between launches. You probably want to ask why I don't use NSUserDefaults or NSKeyedArchiver. Well, I am using NSKeyedArchiver - I don't want to manually override every single setter and getter.

2 Answers
Related