13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Objective-CAdvent Calendar 2012

Day 1

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

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

13
13
0

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
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?