steipete / Aspects

Delightful, simple library for aspect oriented programming in Objective-C and Swift.

Home Page:https://twitter.com/steipete

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

how to hooking a class method?

sayHelloox opened this issue · comments

I find some answer like #20 #27, but I found those can not work, do someone have other solution, thanks!

id object = object_getClass(obj);
[object aspect_...]

can not work for me , What am wrong with me?

id object = object_getClass([TestObject new]);

[object aspect_hookSelector:@selector(testClassMethod) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info){
    NSLog(@"Class method ------ hook");

} error:NULL];

//then call method
[TestObject testClassMethod];

// No log "Class method ------ hook" print

id class = object_getClass(obj);
id metaClass = object_getClass(class);
[metaClass aspect_...]

  1. import <objc/runtime.h>

  2. fetch MetaClass Object

Class settingsMetal = objc_getMetaClass(NSStringFromClass(Settings.class).UTF8String);

  1. hook with the MetaClass Object

    NSError *error = nil;
    [settingsMetal aspect_hookSelector:@selector(hello:) withOptions:AspectPositionBefore usingBlock:^(id info, NSString *hello){

    } error:&error];
    NSLog(@"error %@", error);

Hope this help you !