Swizzle class property?


Shane Stanley
 

The subject more or less says it. I tried using code similar to how I do it with instance methods, to no avail. I'm now wondering if it's actually possible. (It's a read-only property, if that makes a difference.)

+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class theClass = [self class];

SEL originalSelector = @selector(classPropertyName); // name of original property
SEL swizzledSelector = @selector(patchedClassPropertyName); // new method

Method originalMethod = class_getClassMethod(theClass, originalSelector);
Method swizzledMethod = class_getClassMethod(theClass, swizzledSelector);

BOOL didAddMethod =
class_addMethod(theClass,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));

if (didAddMethod) {
class_replaceMethod(theClass,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}



--
Shane Stanley <sstanley@...>
<www.macosxautomation.com/applescript/apps/>, <latenightsw.com>


 



On Aug 25, 2019, at 6:08 PM, Shane Stanley <sstanley@...> wrote:

       if (didAddMethod) {

Shouldn't that be "if (!didAddMethod)" ?

—Jens


Shane Stanley
 

On 27 Aug 2019, at 4:51 am, Jens Alfke <jens@...> wrote:

Shouldn't that be "if (!didAddMethod)" ?
Thank you! It didn't occur to me because it's been working like that elsewhere for several years -- but with an instance method (and different class). Looking again, I'm not sure that class_replaceMethod() branch will ever work. I should probably just call class_addMethod(), and regardless of result call method_exchangeImplementations().

--
Shane Stanley <sstanley@...>
<www.macosxautomation.com/applescript/apps/>, <latenightsw.com>