Skip to content

Instantly share code, notes, and snippets.

@rummelonp
Created January 21, 2011 02:48
Show Gist options
  • Save rummelonp/789168 to your computer and use it in GitHub Desktop.
Save rummelonp/789168 to your computer and use it in GitHub Desktop.
Objective-Cでメソッド定義を差し替えるメソッド
@interface NSObject(Swizzle)
+ (void)swizzleMethod:(SEL)orig_sel withMethod:(SEL)alt_sel;
@end
#import "NSObject+Swizzle.h"
#import <objc/objc-class.h>
@implementation NSObject(Swizzle)
+ (void)swizzleMethod:(SEL)orig_sel withMethod:(SEL)alt_sel
{
Method orig_method = class_getInstanceMethod(self, orig_sel);
Method alt_method = class_getInstanceMethod(self, alt_sel);
if (orig_method == nil || alt_method == nil) {
NSLog(@"method not exists.");
return;
}
class_addMethod(self,
orig_sel,
class_getMethodImplementation(self, orig_sel),
method_getTypeEncoding(orig_method));
class_addMethod(self,
alt_sel,
class_getMethodImplementation(self, alt_sel),
method_getTypeEncoding(alt_method));
method_exchangeImplementations(class_getInstanceMethod(self, orig_sel), class_getInstanceMethod(self, alt_sel));
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment