Quickies

[categories] [index] [all (527)] [latest]

Cocoa Foundation
  1. void Swizzle(Class class, SEL origSel, SEL newSel) {
        Method origMethod = class_getInstanceMethod(class, origSel);
        Method newMethod = class_getInstanceMethod(class, newSel);
    
        if(class_addMethod(class, origSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
            class_replaceMethod(class, newSel, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        } else {
            method_exchangeImplementations(origMethod, newMethod);
        }
    }
    

    from Mike Ash

    static IMP original_initWithString_;
    
    @implementation NSURL (Ext)
    
    + (void)swizzleMethods { // call this once, early
        original_initWithString_ = method_getImplementation(class_getInstanceMethod([self class], @selector(initWithString:)));
        Swizzle([self class], @selector(initWithString:), @selector(my_initWithString:));
    }
    
    // -[NSURL urlWithString:] will now execute this method
    - (NSURL *)my_initWithString:(NSString *)s {
        NSLog(@"-- my_initWithString: %@", s);
        return original_initWithString_(self, @selector(initWithString:), s);
    }
    
    @end