LoginSignup
13

More than 5 years have passed since last update.

Methodの処理を差し替える - MethodSwizzling

Last updated at Posted at 2012-12-02

はじめまして、おでんです。
なんかAdvent Calendarってのが流行ってるらしいので、乗っかってみました。

MethodSwizzlingは、Methodで行われる処理を差し替える手段のひとつです。
iOS向けの単純なサンプルを載せておきますので、実行してみて頂けると幸いです。

main.m
#import <objc/runtime.h>

@interface Test : NSObject

-(void)instanceMethod;

@end

@implementation Test

-(void)instanceMethod
{
    NSLog(@"instanceMethod");
}

@end

int main(int argc, char *argv[])
{
    @autoreleasepool
    {
        id block = ^{ NSLog(@"block"); };
        id class = [Test class];
        SEL sel = @selector(instanceMethod);
        IMP imp = imp_implementationWithBlock(block);
        Method method = class_getInstanceMethod(class, sel);
        char* types = method_getDescription(method)->types;

        id test = [[[Test alloc] init] autorelease];
        [test instanceMethod]; // NSLog(@"instanceMethod");
        class_replaceMethod(class, sel, imp, types);
        [test instanceMethod]; // NSLog(@"block);

        return 0;
    }
}

MethodSwizzlingについて調べると長い説明から入ることが多く、
取っ付きにくい印象を受けている人が多いように感じられます。
なので取りあえずどうすれば動くのかだけを書いてみました。

説明なんてもんは飾りです。
エライ人にはそれがわからんのですよ。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13